如果要找大于等于target的第一个数:
public int binarySearch (int[] nums, int target) {
if(nums.length == 0) return 0;
int left = 0, right = nums.length - 1;
while(left < right){
int mid = left + right >> 1;
if(nums[mid] >= target) right = mid;
else left = mid + 1;
}
return right;
}
如果要找小于等于target的最后一个数:
public int binarySearch (int[] nums, int target) {
if(nums.length == 0) return 0;
int left = 0, right = nums.length - 1;
while(left < right){
int mid = left + right + 1>> 1;
if(nums[mid] <= target) left = mid;
else right = mid - 1;
}
return left;
}