69. x 的平方根
class Solution {
public int mySqrt(int x) {
// 注意细节处理0的问题
if(x < 1) return 0;
long left = 0,right = x;
while(left < right){
long mid = left + (right -left+1)/2;
if(mid * mid <=x) left = mid ;
else right = mid -1;
}
return (int)left;
}
}
35. 搜索插入位置
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0,right = nums.length-1;
while(left<right){
int mid = left +(right-left)/2;
if(nums[mid] < target) left = mid+1;
else right =mid;
}
//处理第三种情况
if(nums[left]<target) return left+1;
return left;
}
}
852. 山脉数组的峰顶索引
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left=0,right=arr.length-1;
while(left<right){
int mid = left+(right-left+1)/2;
if(arr[mid]>arr[mid-1])left = mid;
else right = mid-1;
}
return left;
}
}
162. 寻找峰值
class Solution {
public int findPeakElement(int[] arr) {
int left=0,right=arr.length-1;
while(left<right){
int mid = left+(right-left)/2;
if(arr[mid]>arr[mid+1]) right = mid;
else left = mid+1;
}
return left;
}
}
153. 寻找旋转排序数组中的最小值
class Solution {
public int findMin(int[] nums) {
int left=0,right=nums.length-1;
int n=nums.length-1;
while(left<right){
int mid=left+(right-left)/2;
if(nums[mid]>nums[n]) left=mid+1;
else right=mid;
}
return nums[left];
}
}
我们再讨论一下是否能将A点作为参考点:
class Solution {
public int findMin(int[] nums) {
int left=0,right=nums.length-1;
if(nums[0]<nums[right])return nums[0];
while(left<right){
int mid=left+(right-left)/2;
if(nums[mid]>=nums[0]) left=mid+1;
else right=mid;
}
return nums[left];
}
}
LCR 173. 点名
class Solution {
public int takeAttendance(int[] nums) {
int left=0,right=nums.length-1;
if(nums[right]==right) return right+1;
while(left<right){
int mid=left+(right-left)/2;
if(nums[mid]==mid) left=mid+1;
else right=mid;
}
return left;
}
}