162 Find Peak Element

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

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

Solution

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

Notes
注意有peak element的子数组的特点:必定有nums[istart] < nums[istart+1]nums[end] < nums[end-1]。基于这个关系采用二分搜索缩小检索范围。

results matching ""

    No results matching ""