LeetCode 162. Find Peak Element(二分)

topic

Meaning of the questions: an array of adjacent elements are not equal, so that you find this array hump, hump is this element is larger than the adjacent elements.

Solution: binary search, if you find a small element than the left adjacent elements, then there must be left hump, empathy, the right also. Through this law will be a half.

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

Guess you like

Origin www.cnblogs.com/dacc123/p/12221454.html