leetcode162---Find Peak Element(找峰值点)

来源:互联网 发布:h5页面制作软件 知乎 编辑:程序博客网 时间:2024/05/29 18:22

问题描述:

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.

问题求解:

二分求解。

class Solution {public:    int findPeakElement(vector<int>& nums) {        int low=0;        int high=nums.size()-1;        while(low < high)        {            int mid=low + (high-low)/2;            if(nums[mid] < nums[mid+1])            {//(1)mid~mid+1处在上升区间,由于num[n] = -∞,其后必有下降区间                low = mid+1;//该区间必有峰值,搜索mid+1~hig区间            }            else            {//(2)同理                high = mid;            }        }//退出循环时low>=high,从(1)(2)知low为峰值点        return low;    }};
0 0