[LeetCode] Search for a Range 搜索一个范围
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为O(logn),这是典型的二分查找法的时间复杂度,所以这道题我们也需要用此方法,我们的思路是首先对原数组使用二分查找法
使用两次二分查找法,第一次找到左边界,第二次调用找到右边界即可
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] ret = new int[2];
Arrays.fill(ret, - 1);
if(nums.length == 0)
return ret;
int l = 0, h = nums.length - 1;
//找左边界,让l变化 h不断从右边靠拢至左边,l正好停在l=h =左边界上 比如88888
while(l < h){
int m = l + (h-l) / 2;
if(nums[m] < target){
l = m + 1;
}
else
h = m;
}
//说靠拢之后 l=h != target 不存在左边界说明没有一个与target相等的值 即没有等于target的值 说明不存在目标值
if(nums[h] != target)
return ret;【-1, -1】
ret[0] = h;
h = nums.length;
//按此时寻找右边界 当让h始终是右边界值右边的那个值 比如 888899 h最后就收敛到9
//l每次会增大 从左边界不断增长到右边界再到右边界右边的值 8-8-8-8-9 结束
while(l < h){
int m = l + (h - l) / 2;
if(nums[m] > target)
h = m;
else
l = m + 1;
}
ret[1] = l - 1; //取出右边界
return ret;
}
}