标签(空格分隔): leetcode array
题目
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.
Your solution should be in logarithmic complexity.
思路
这道题目由于题目的特殊性,因此我们可以确定该数组必定存在peak,然后我们可以应用二分搜索。唯一要注意的是这里要维护两个中间值middle1,middle2,通过比价这两个值来决定接下来的迭代方向。
代码class Solution {
public:
int findPeakElement(vector<int>& nums) {
int start=0,end=nums.size()-1;
while(start<end)
{
int middle1=(start+end)/2;
int middle2=middle1+1;
if(nums[middle1]>nums[middle2])
end=middle1;
else
start=middle2;
}
return start;
}
};