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.
該題是在一個相鄰元素不相等的數組,找出其中的一個局部最大值,返回其對應下標,要求時間複雜度爲O(lgN)。因此,可以採用二分查找法,即:如
果中間元素大於其相鄰後續元素,則中間元素左側(包含該中間元素)必包含一個局部最大值。如果中間元素小於其相鄰後續元素,則中間元素右側必
包含一個局部最大值。
代碼:
#include <iostream>
#include <vector>
using namespace std;
int findPeakElement(const vector<int> &num)
{
int left=0,right=num.size()-1;
while(left <= right)
{
if(left == right) return left;
int mid = (left + right) / 2;
if(num[mid] < num[mid+1])
left = mid+1;
else
right = mid;
}
}
int main()
{
vector<int> num;
int x;
while(cin >> x)
{
num.push_back(x);
}
cout<<findPeakElement(num);
}