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]
.
解题思路:二分查找
public int[] searchRange(int[] nums, int target) {
int arr[] = {-1,-1};
if(target < nums[0]) return arr;
int start = 0;
int end = nums.length-1;
int index = -1;
while (start <= end){
int mid = (start+end)/2;
if(nums[mid] < target){
start = mid + 1;
}else if(nums[mid] > target){
end = mid - 1;
}else {
index = mid;
break;
}
}
if(index == -1) return arr;
arr[0] = index;
arr[1] = index;
for(int i = index-1; i >= 0; i--){
if(nums[i] == target){
arr[0] = i;
}
}
for(int i = index+1; i < nums.length; i++){
if(nums[i] == target){
arr[1] = i;
}
}
return arr;
}