Update BinarySearch.java
parent
feb1f5fcad
commit
a3f5a177a5
|
|
@ -91,6 +91,7 @@ class BinarySearch {
|
|||
return candidate;
|
||||
}
|
||||
|
||||
//改进二分查找
|
||||
public static int binarySearchLeftMost0(int[] nums, int target) {
|
||||
int i = 0, j = nums.length - 1;
|
||||
while (i <= j) {
|
||||
|
|
@ -116,4 +117,25 @@ class BinarySearch {
|
|||
}
|
||||
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};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue