题目
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],如果找到了,再找右边界。
代码
public class SearchForARange {
public int[] searchRange(int[] A, int target) {
if (A == null || A.length == 0) {
return new int[] { -1, -1 };
}
int low = 0;
int high = A.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (A[mid] >= target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
int left = (low < A.length && A[low] == target) ? low : -1;
if (left == -1) {
return new int[] { -1, -1 };
}
low = 0;
high = A.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (A[mid] <= target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return new int[] { left, high };
}
}