问题描述:
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.
Note:
如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。(可通过反证法证明该方法的正确性)
Your solution should be in logarithmic complexity.
问题分析:
过程详见代码:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int low = 0;
int high = nums.size()-1;
while(low < high)
{
int mid1 = (low+high)/2;
int mid2 = mid1+1;
if(nums[mid1] < nums[mid2])
low = mid2;
else
high = mid1;
}
return low;
}
};
本文介绍了一种在给定数组中寻找峰值元素的算法,峰值元素定义为大于其邻居的元素。文章提供了一个解决方案,该方案使用二分查找法在对数时间内找到峰值的位置。
368

被折叠的 条评论
为什么被折叠?



