题目描述:
Given an array of integers sorted in ascending order, 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].
题目分析:
是Search Insert Position的变形,就是找边界情况。
一共做三次binary search. 第一次试着找target, 若是找到了就存index在res 中, index对应的是边界还是中间的target 不重要。若是找不到直接返回res.
第二次找左边界,在 l = 0 和 target index 中间找,若是取得mid 位置上不等于target 说明左边界应该在后半部分找,若是等于target说明左边界应该在前半部找。
第三次找右边界,道理同上.
代码:
public class Solution {
public int[] searchRange(int[] nums, int target) {
int [] res = {-1,-1};
if(nums == null || nums.length == 0){
return res;
}
//find target index
int l = 0;
int r = nums.length-1;
while(l<=r){
int mid = l+(r-l)/2;
if(nums[mid] == target){
res[0] = mid;
res[1] = mid;
break;
}else if (nums[mid] > target){
r = mid-1;
}else{
l = mid+1;
}
}
//if can't find target
if(res[0] == -1){
return res;
}
l = 0;
r = nums.length -1;
int pos = res[0];
//find the left bound
while(l<=pos){
int mid = l+(pos-l)/2;
if(nums[mid] == target){
pos = mid-1;
}else{
l = mid+1;
}
}
res[0] = l;
//find the right bound
pos = res[1];
while(pos<=r){
int mid = pos + (r-pos)/2;
if(nums[mid] == target){
pos = mid+1;
}else{
r = mid-1;
}
}
res[1] = r;
return res;
}
}
寻找目标区间
本文介绍了一种在有序整数数组中查找指定目标值起始和结束位置的方法,通过三次二分查找实现,确保了算法的时间复杂度为O(logn)。
1619

被折叠的 条评论
为什么被折叠?



