Optimal: two bound searches
Time O(log n) Space O(1)first = lowerBound(target). If first is n or nums[first] != target, return [-1, -1]. Otherwise last = upperBound(target) − 1.
class Solution {
public int[] searchRange(int[] nums, int target) {
int first = bound(nums, target, false);
if (first == nums.length || nums[first] != target) return new int[]{-1, -1};
int last = bound(nums, target, true) - 1;
return new int[]{first, last};
}
// first index with nums[i] >= t (upper == false) or nums[i] > t (upper == true)
private int bound(int[] nums, int t, boolean upper) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > t || (!upper && nums[mid] == t)) hi = mid;
else lo = mid + 1;
}
return lo;
}
}Verdict: Two binary searches, no linear scan.