1 二分查找
Leetcode704
1 [l,r]区间 l = 0, r = nums.length-1; while(l<=r) 因为l==r有意义
2 [l,r)区间 l = 0, r = nums.length; while(l<r)
Leetcode35
class Solution {public int searchInsert(int[] nums, int target) {int l=0,r=nums.length;while(l<r){int m = l+(r-l)/2;if(nums[m]==target){return m;}else if(nums[m]<target){l = m+1;}else{r = m;}}return l;}
}
Leetcode34
class Solution {public int[] searchRange(int[] nums, int target) {int[] res = {-1,-1};int l=0,r = nums.length;while(l<r){int m = l + (r-l)/2;if(nums[m]<=target){l=m+1;}else{r = m;}}if(l-1>=0&&nums[l-1]==target){res[1] = l-1;for(int i=l-1;i>=0;i--){if(nums[i]==target){res[0] = i;}else{break;}}} return res;}
}
Leetcode69
class Solution {public int mySqrt(int x) { int l=0,r=x;if(x<=1)r++;while(l<r){int m = l+(r-l)/2;if((long)m*m>x){r = m;}else{l = m+1;}}return l-1;}
}
Leetcode367
class Solution {public boolean isPerfectSquare(int num) {int l=0,r=num;while(l<=r){int m = l+(r-l)/2;if((long)m*m==num){return true;}else if((long)m*m<num){l = m+1;}else{r = m-1;}}return false;}
}
2 移除元素
Leetcode27
快慢指针 每轮循环不相等fast++ slow++并赋值 相等fast++