My 5 lines C++


  • 0

    My O(n) solution

        int findPeakElement(vector<int>& nums) {
            nums.insert(nums.begin(),INT_MIN);
            nums.push_back(INT_MIN);
            for(int i=1;i<nums.size();i++)
                if(nums[i]>nums[i-1]&&nums[i]>nums[i+1]) return i-1;
            return 0;
        }
    

    Just for clear up, solutions below are from this post.
    O(logn) binary search

    int findPeakElement(const vector<int> &num) {
        return Helper(num, 0, num.size()-1);
    }
    int Helper(const vector<int> &num, int low, int high)
    {
        if(low == high)
            return low;
        else
        {
            int mid1 = (low+high)/2;
            int mid2 = mid1+1;
            if(num[mid1] > num[mid2])
                return Helper(num, low, mid1);
            else
                return Helper(num, mid2, high);
        }
    }
    

    O(n) sequential search

        int findPeakElement(const vector<int> &num) {
            for(int i = 1; i < num.size(); i ++)
            {
                if(num[i] < num[i-1])
                {// <
                    return i-1;
                }
            }
            return num.size()-1;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.