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]
在有序数组中查找数字出现的首末位置
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int[] ret = new int[]{-1, -1};
if(right < 0) {
return ret;
}
int mid = right / 2;
while(nums[mid] != target) {
if(nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
if(left > right) {
return ret;
}
int temp = (right - left) / 2;
mid = left + temp;
}
left = mid - 1;
right = mid + 1;
while(left >= 0 && nums[left] == target) {
left--;
}
ret[0] = left + 1;
while(right <nums.length && nums[right] == target) {
right++;
}
ret[1] = right - 1;
return ret;
}
}