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.
找peak,这里不能单纯的根据start mid来判断用start还是end替换mid,应该根据斜率,mid跟mid+1去比,<替换start,>=替换end。同样需要判断0和length-1的情况。代码如下:
public class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) {
return 0;
}
if (nums[0] > nums[1]) {
return 0;
}
if (nums[nums.length - 1] > nums[nums.length - 2]) {
return nums.length - 1;
}
int lb = 0, ub = nums.length - 1;
while (lb + 1 < ub) {
int mid = lb + (ub - lb) / 2;
int mid2 = mid + 1;
if (nums[mid] < nums[mid2]) {
lb = mid;
} else {
ub = mid;
}
}
return lb + 1;
}
}