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]
二分法傻瓜模板:用一个res记录可能的答案,whlie(s<=e), start = mid+1; end = mid - 1即可。不需要考虑什么时候+1,什么时候保持不变。。。
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1,-1};
if (nums.length == 0) return res;
res[0] = search(nums, target, true);
res[1] = search(nums, target, false);
return res;
}
public int search(int[] nums, int target, boolean first) {
if (nums.length == 1) return nums[0] == target ? 0 : -1;
int start = 0;
int end = nums.length - 1;
int res = -1;
while (start <= end) {
int mid = (end - start) / 2 + start;
if (nums[mid] == target) {
res = mid;
if (first) end = mid - 1;
else start = mid + 1;
} else if (nums[mid] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return res;
}
}