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.

这个题目出的还是真是让人难以理解题意...

题意是找出任意一个峰值,题目要求时间复杂度是o(lgn);

这种时间复杂度也就是告诉我们用二分。

二分的思想就是区间裁剪。在这里,如果中点值大于右边第一个值,那么裁掉右边区间,为什么呢?

因为num[-1] = -∞,

那么num[mid]>num[-1] && num[mid]>num[mid+1],

所以在[1,mid]这个区间一定会存在一个峰值

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

 

posted @ 2015-11-29 02:00  zengzy  阅读(129)  评论(0编辑  收藏  举报
levels of contents