注意:寻找完边界后,要判断两者是否合法!!!
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) {
return new int[]{-1, -1};
}
int leftBound = findLeftBound(nums, target, 0, nums.length - 1);
int rightBound = findRightBound(nums, target, 0, nums.length - 1);
if (leftBound <= rightBound) {
return new int[]{leftBound, rightBound};
}
return new int[]{-1, -1};
}
public int findLeftBound(int[] nums, int target, int left, int right) {
int mid = 0;
while (left <= right) {
mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
public int findRightBound(int[] nums, int target, int left, int right) {
int mid = 0;
while (left <= right) {
mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right;
}
}