C++ concise solution using binary search standard templates


  • 0
    S

    Only things that we need to care about are a few base cases. Please pay attention to the fact that num[-1] = num[n] = -∞.

    Next thing is to use very standard binary search template. That's it.

    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            if(nums.size() == 0 || nums.size() == 1) return 0;
            int l = 0, r = nums.size() - 1;
            if(nums[0] > nums[1]) return 0;
            if(nums[r] > nums[r-1]) return r;
            while(l <= r){
                int mid = (l + r)/2;
                if(nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) return mid;
                if(nums[mid] > nums[mid - 1]){
                    l = mid + 1;
                }else{
                    r = mid - 1;
                }
            }
        }
    };

Log in to reply
 

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