首页 > 其他 > 详细

Find Peak Element

时间:2015-11-29 06:27:16      阅读:201      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

Find Peak Element

原文:http://www.cnblogs.com/zengzy/p/5003941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!