Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
tag:array, binary search
method 1
遍历数组,得到最小最大
method 2 binary search
首先,按照正常binary search首先在mid处找到一个target,因为数组已经排序好了,如果还有其他的target,那一定是在target的左边还有右边,如果有,那就分别以mid-1作为最右边界/mid+1作为最左边界继续查找,得到position更小/更大的数
public int[] searchRange(int[] nums, int target) {
int first = Integer.MAX_VALUE, last = Integer.MIN_VALUE;
int[] ans = searchRange(nums, target, 0, nums.length - 1,first,last);
if (ans[0] == Integer.MAX_VALUE)
return new int[]{-1,-1};
return ans;
}
public int[] searchRange(int[] num, int target, int l, int r, int first, int last) {
if (l > r) return new int[]{first, last};
int mid = (l + r) / 2;
if (num[mid] == target){
first = Math.min(first,mid);
last = Math.max(last,mid);
int[] ans = new int[2];
if (mid > 0 && num[mid-1] == target){
ans = searchRange(num,target,l,mid-1,first,last);
first = Math.min(first,ans[0]);
}
if (mid < num.length-1 && num[mid+1] == target){
ans = searchRange(num,target,mid+1,r,first,last);
last = Math.max(last,ans[1]);
}
return new int[]{first,last};
} else if (num[mid] > target)
return searchRange(num, target, l, mid-1, first, last);
else return searchRange(num, target, mid+1, r, first, last);
}
summary
- 有序数组中查找数,很自然地就想到binary search