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.
一刷
题解:由于左右边界都是洼地。我们最终输出lo所在位置。所以,当找到一个点大于其左邻点,将lo置为该点。否则,将hi置为该邻点(不能再用lo,避免不能跳出循环,因为只要找到一个满足条件的点就可以)。
public class Solution {
public int findPeakElement(int[] nums) {
int lo = 0, hi = nums.length-1;
while(lo<hi){
int mid1 = (lo+hi)/2;
int mid2 = mid1+1;
if(nums[mid1]<nums[mid2]) lo = mid2;
else hi = mid1;
}
return lo;
}
}
二刷
思路同上
public class Solution {
public int findPeakElement(int[] nums) {
int lo = 0, hi = nums.length-1;
while(lo<hi){
int mid = lo + (hi-lo)/2;
int mid2 = mid+1;
if(nums[mid]>nums[mid2]) hi = mid;
else lo = mid2;
}
return lo;
}
}