刷
June-21-2019
最早的时候被边界条件各种恶心。
YLNR大法,注意最后的边界。
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0 || nums[0] > target || nums[nums.length - 1] < target) {
return new int[]{-1, -1};
}
int l = 0, r = nums.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] >= target) {
r = m - 1;
} else {
l = m + 1;
}
}
int[] result = new int[]{-1, -1};
if (nums[l] != target) {
return result;
} else {
result[0] = l;
}
l = 0;
r = nums.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] <= target) {
l = m + 1;
} else {
r = m - 1;
}
}
result[1] = r;
return result;
}