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]
给出一个升序数组,让找到给定数字target的起始位置(有重复的数字)
思路:
binary search,用不同的比较方法来找到起始位置
//0ms
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1, -1};
int n = nums.length;
if(n == 0) return res;
int left = 0;
int right = n;
while(left < right) {
int mid = left + (right - left) / 2;
if(nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
if(left >= n || nums[left] != target) return res;
res[0] = left;
left = 0;
right = n;
while(left < right) {
int mid = left + (right - left) / 2;
if(nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
left --;
if(left < 0 || nums[left] != target) res[1] = res[0];
else res[1] = left;
return res;
}