Find Peak Element
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
SOLUTION 1:
线性查找,时间O(N):
public int findPeakElement1(int[] num) {
if (num == null) {
return 0;
} if (num.length == 1) {
return 0;
} for (int i = 0; i < num.length; i++) {
if (i == 0) {
if (num[i] > num[i + 1]) {
return i;
}
continue;
} if (i == num.length - 1) {
if (num[i] > num[i - 1]) {
return i;
}
continue;
} if (num[i] > num[i + 1] && num[i] > num[i - 1]) {
return i;
}
} return -1;
}
SOLUTION 2:
使用九章算法的二分法模板,可以达到O(logN)的时间复杂度。原理是:
当找到一个下坡,我们往左移动,当找到一个上坡,我们往右移动,这样我们就可以达到顶峰。
如果找到一个山谷,则向任意方向移动即可。
4
3 3 5
2 2 2
1 1
如上图所示,3,4都是可能的解。
最后循环break时,把l,r的值找一个大的即可。
public int findPeakElement(int[] num) {
if (num == null) {
return 0;
} if (num.length == 1) {
return 0;
} int l = 0;
int r = num.length - 1; while (l < r - 1) {
int mid = l + (r - l) / 2;
if (num[mid] > num[mid + 1] && num[mid] > num[mid - 1]) {
return mid;
} if (num[mid] > num[mid - 1] && num[mid] < num[mid + 1]) {
// rising area. move right;
l = mid;
} else if (num[mid] < num[mid - 1] && num[mid] > num[mid + 1]) {
r = mid;
} else {
l = mid;
}
} return num[l] > num[r] ? l: r;
}
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/binarySearch/FindPeakElement.java