给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
- 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
没啥说的
public int[] searchRange(int[] nums, int target) {
int[] answer = {-1, -1};
int length = nums.length;
if (length == 0) return answer;
int left = 0, right = length-1, middle;
while (left <= right) {
middle = (left + right) / 2;
if (nums[middle] == target) {
left = right = middle;
while (left >= 0 && right <= length-1) {
if (left-1 >= 0 && nums[left-1] == nums[left]) {
-- left;
} else if (right+1 <= length-1 && nums[right] == nums[right+1]) {
++ right;
} else {
answer[0] = left;
answer[1] = right;
break;
}
}
break;
}
if (nums[middle] < target) {
left = middle+1;
} else {
right = middle-1;
}
}
return answer;
}