Y总的模板太强大了,当初的我蛋疼地调了好久好久~~~
来看下实现:
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) {
return new int[]{-1, -1};
}
int[] ans = new int[2];
int n = nums.length;
int l = 0, r = n - 1;
while (l < r){
int mid = l + r >>> 1;
// left
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
if (nums[l] != target) {
return new int[]{-1, -1};
}
ans[0] = l;
l = 0;
r = n - 1;
while (l < r){
int mid = l + r + 1 >>> 1;
// right
if (nums[mid] <= target) l = mid;
else r = mid - 1;
}
ans[1] = r;
return ans;
}
}