码迷,mamicode.com
首页 > 其他好文 > 详细

Find Peak Element

时间:2015-11-29 06:27:27      阅读:170      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!