Description
Given an array of integers 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
Solution
Binary search
注意返回right还是left哦。
class Solution {
public int[] searchRange(int[] nums, int target) {
int firstIndex = search(nums, target, true);
if (firstIndex >= nums.length || nums[firstIndex] != target) {
return new int[]{-1, -1};
}
int lastIndex = search(nums, target, false);
int[] res = new int[2];
res[0] = firstIndex;
res[1] = lastIndex;
return res;
}
public int search(int[] nums, int target, boolean isFirst) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target > nums[mid] || (target == nums[mid] && !isFirst)) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return isFirst ? left : right;
}
}