LeetCode34. 在排序数组中查找元素的第一个和最后一个位置
- 题目跳转
- 二分边界问题参考
- JAVA代码:
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) return new int[]{-1, -1};
int[] res = new int[2];
res[0] = binarySearchFirst(nums, target, 0, nums.length);
res[1] = res[0] == -1 ? -1 : binarySearchSecond(nums, target, 0, nums.length);
return res;
}
//查找左边界
private int binarySearchFirst(int[] nums, int target, int left, int right) {
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] >= target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
if (left == nums.length) return -1;
return nums[left] == target ? left : -1;
}
//查找右边界
private int binarySearchSecond(int[] nums, int target, int left, int right) {
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) {
right = mid;
} else if (nums[mid] <= target) {
left = mid + 1;
}
}
if (left == 0) return -1;
return nums[left - 1] == target ? (left - 1) : -1;
}
}