二分查找、二分边界
二分查找
public int binarySearch(int[]nums, int target){
int left = 0;
int right = nums.length-1;
while (left<=right){
int mid = left + (right-left)/2;
if (nums[mid]==target){
return mid;
}else if (nums[mid]>target){
right = mid - 1;
} else {
left = mid + 1;
}
}
if (left>nums.length){
return -1;
}
return nums[left] == target?left:-1;
}
左边界
若有target,返回最左边的那个的下标。若无target,返回第一个大于target的下标(查找第一个大于等于 target 的下标)
public int leftBound(int[]nums, int target){
int left = 0;
int right = nums.length-1;
while (left<=right){
int mid = left + (right-left)/2;
if (nums[mid]<target){
left = mid + 1;
} else {
right = mid - 1;
}
}
return left < nums.length?left:-1;
}
右边界
若有target,返回最右边的那个的下标。若无target,返回最后一个小于target的下标(查找最后一个小于等于 target 的下标)
public int rightBound(int[]nums, int target){
int left = 0;
int right = nums.length-1;
while (left<=right){
int mid = left + (right-left)/2;
if (nums[mid]>target){
right = mid - 1;
} else{
left = mid + 1;
}
}
return right >= 0?right:-1;
}