xinyu04

导航

LeetCode 162 Find Peak Element 二分

A peak element is an element that is strictly greater than its neighbors.

Given a \(0\)-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in \(O(\log n)\) time.

Solution

找到数组中的 \(peak\). 考虑二分的过程 \(mid\),有三种情况:

  • \(a[mid]=peak\)
  • \(a[mid]<a[mid-1]\)
  • \(a[mid]<a[mid+1]\)

所以我们在二分出 \(mid\) 的时候,分别判断就好

点击查看代码
class Solution {
private:
    int ans=0;
public:
    int findPeakElement(vector<int>& nums) {
        int n = nums.size();
        if(n==1) return 0;
        int l = 0, r = n-1;
        if(nums[0]>nums[1]) return 0;
        if(nums[n-1]>nums[n-2]) return n-1;
        int mid;
        while(l<=r){
            mid = l+(r-l)/2;
            if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1])
                return mid;
            
            if(nums[mid]<nums[mid-1]) r = mid;
            else if(nums[mid]<nums[mid+1]) l =mid+1;
        }
        return mid;
    }
};

posted on 2022-07-29 18:49  Blackzxy  阅读(15)  评论(0编辑  收藏  举报