class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 1, right = arr.length - 2;
while(left < right){
int mid = left + (right - left + 1) / 2;
if(arr[mid] > arr[mid - 1]) left = mid;
else right = mid - 1;
}
return left;
}
}
class Solution {
public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] > nums[mid + 1]) right = mid;
else left = mid + 1;
}
return left;
}
}
解法二: 利用二段性将数组分为两段,AB段和CD段,都是呈上升趋势,且CD段最后一个值(标记为 x )小于AB段的值,所以找最小值 要到CD段里找.
当arr[mid] > x,说明此时mid在AB段,更新left= mid+ 1;
当arr[mid] < x,说明此时mid在CD段,更新right= mid;
画图举例
代码
复制代码
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
int x =nums[right];//标记最后位置的值
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] > x) left = mid + 1;
else right = mid;
}
return nums[left];
}
}
class Solution {
public int takeAttendance(int[] records) {
int left = 0, right = records.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(records[mid] == mid) left = mid + 1;
else right = mid;
}
if(left == records[left]) return left + 1;
return left;
}
}