[Array]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.

方法:按照二分查找的思路进行。注意题中所给的条件,num[i] ≠ num[i+1],并且可能存在多个Peak Element,只要返回其中一个下标即可。

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

    }
};
posted @ 2016-07-21 08:43  U_F_O  阅读(157)  评论(0编辑  收藏  举报