Update BinarySearch.java

master
wangsiyuan 2024-07-11 10:41:28 +08:00
parent feb1f5fcad
commit a3f5a177a5
1 changed files with 22 additions and 0 deletions

View File

@ -91,6 +91,7 @@ class BinarySearch {
return candidate; return candidate;
} }
//改进二分查找
public static int binarySearchLeftMost0(int[] nums, int target) { public static int binarySearchLeftMost0(int[] nums, int target) {
int i = 0, j = nums.length - 1; int i = 0, j = nums.length - 1;
while (i <= j) { while (i <= j) {
@ -116,4 +117,25 @@ class BinarySearch {
} }
return i - 1; return i - 1;
} }
/**
* nums target
* target [-1, -1]
* O(log n)
*
* @param nums
* @param target
* @return
*/
public static int[] searchRange(int[] nums, int target) {
if (nums.length == 0){
return new int[]{-1,-1};
}
if (nums.length == 1){
return new int[]{0,0};
}
int left = binarySearchLeftMost(nums, target);
int right = binarySearchRightMost(nums,target);
return new int[]{left,right};
}
} }