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.
O(n)的方法很简单,甚至觉得不应该对应Medium难度。
class Solution {
public:
int findPeakElement(const vector<int> &num) {
if (num.size() <= 1) {
return 0;
}
for (int i = 1; i < num.size(); ++i) {
if (num[i] < num[i-1]) {
return i - 1;
}
}
return num.size() - 1;
}
};
后来发现要求O(logn)的方法。运算符优先级弄错了,鼓捣半天,>>的优先级小于四则运算的。另外一个点,mid+1是一定存在的,这个可以简化问题。
class Solution {
public:
int findPeakElement(const vector<int> &num) {
int low = 0;
int up = num.size() - 1;
while (low < up) {
int mid1 = low + (up - low) / 2;
int mid2 = mid1 + 1;
if ((mid1 == 0 || num[mid1] > num[mid1-1]) && num[mid1] > num[mid2]) {
return mid1;
}
if (num[mid1] > num[mid2]) {
up = mid1;
}
else {
low = mid2;
}
}
return low;
}
};
还有一种想法,只要元素个数大于2,那么mid-1和mid+1一定都存在。
class Solution {
public:
int findPeakElement(const vector<int> &num) {
int low = 0;
int up = num.size() - 1;
while (low < up) {
if (low + 1 == up) {
return num[low] > num[up] ? low : up;
}
int mid = low + (up - low) / 2;
if (num[mid] > num[mid-1] && num[mid] > num[mid+1]) {
return mid;
}
else if (num[mid] > num[mid-1]) {
low = mid;
}
else if (num[mid] > num[mid+1]) {
up = mid;
}
else {
up = mid - 1;
}
}
return low;
}
};