Search for a Range
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]
.
Solution1:
public int[] searchRange(int[] nums, int target) {
int max = nums.length - 1;
int begin = 0;
int end = max;
while (begin < max && nums[begin] != target) {
begin++;
}
while (end > -1 && nums[end] != target) {
end--;
}
if (end < begin) {
return new int[] { -1, -1 };
} else {
return new int[] { begin, end };
}
}
Solution2:
public int[] searchRange(int[] A, int target) {
int start = firstGreaterEqual(A, target);
if (start == A.length || A[start] != target) {
return new int[] { -1, -1 };
}
return new int[] { start, firstGreaterEqual(A, target + 1) - 1 };
}
private int firstGreaterEqual(int[] A, int target) {
int low = 0, high = A.length;
while (low < high) {
int mid = low + ((high - low) >> 1);
if (A[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}