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]
题目:给定一个有序数组和一个目标值,找出数组中该目标值左右边界的位置,如果不存在则输出[-1,-1]。要求时间复杂度是O(log n)。
思路:既然时间复杂度是O(log n),那就必须要用到二分法,用二分法找到一个目标值,在前后遍历,找到不同的那个位置即可。
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int[] num = {-1, -1};
while(left <= right) {
int mid = (right + left)/2;
if(nums[mid] == target) { //找到目标,不用管是哪一个
int plus = mid,jian = mid;
while(plus < nums.length && nums[plus] == target) {//找到目标值后开始往前往后遍历,找到两个临界点
plus++;
}
num[1] = plus-1;
while(jian >= 0 && nums[jian] == target) {
jian--;
}
num[0] = jian+1;
break;
}else if(nums[mid] < target) {
left = mid+1;
} else {
right = mid-1;
}
}
return num;
}