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.

自己测试了一些特殊用例
[7, 6, 5, 4, 3, 2, 3, 2, 1]
结果为0
[1, 2, 3, 2, 3, 4, 5, 6, 7]
结果为7
也就是说峰值是可以在开头和结尾处的,不一定非是
[2, 3, 1]这种类型的
class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int lb = 0; 
        int ub = nums.size() - 1;

        while(lb < ub){
            int mid1 = lb + (ub - lb)/2;
            int mid2 = mid1 + 1;

            if(nums[mid1] < nums[mid2])
                lb = mid2;
            else
                ub = mid1;
        }
        return lb;
    }
};

results matching ""

    No results matching ""