您的位置:首页 > 其它

LeetCode 162 Find Peak Element

2015-04-03 00:27 459 查看
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
= -∞
.

For example, in array 
[1, 2, 3, 1]
, 3 is a peak element and your function should return the
index number 2.

click to show spoilers.

Note:
Your solution should be in logarithmic complexity.

题目本身不难,要求对数复杂度求解。

不会做。。。于是看看网上的题解,没咋看懂,和同学讨论讨论有点明白了。

题目我理解像题目的名字一样,找峰值,那就画一座山,把值理解为高度,且没有相邻的两点高度一样
(num[i] ≠ num[i+1])
,两边是万丈深渊(
num[-1] = num
= -∞
),在对数复杂度内找到一个山峰,找的一个即可,是存在性问题。对数的话,第一感觉就是二分法,如何证明二分法有效呢?上图:



假设高度是连续的,有题我们可以得出,最左边的的斜率k>0,最右边k<0,由二分法得出的中点处mid,计算mid和右边或左边相邻点的斜率由其符号可知在左或右边一定存在斜率由正到负或者负到正的跳变,跳变处即是峰值,解出一个峰值即可。

上码,注意一些细节的处理:

class Solution {
public:
int findPeakElement(const vector<int> &num) {
int l = 0;
int r = num.size()-1;
int mid;

while(l < r)
{
mid = (l+r)/2;

if(num[mid]<num[mid+1])
l = mid+1;
else r = mid;
}

return l;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: