LeetCode34 在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
LeetCode34
示例1
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例2
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例3
输入:nums = [], target = 0
输出:[-1,-1]
解答思路
记录做题逐步完善过程
Solution 1
找到相等位置,然后向两边延伸找到左右边界
public int[] searchRange1(int[] nums, int target) {
int[] ret = {-1, -1};
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (target == nums[mid]) {
int start = mid;
// traverse to find left bound
while (left < start && nums[start] == nums[start - 1]) {
start--;
}
int end = mid;
// traverse to find right bound
while (end < right && nums[end] == nums[end + 1]) {
end++;
}
ret[0] = start;
ret[1] = end;
break;
} else if (target > nums[mid]){
left = mid + 1;
} else {
right = mid - 1;
}
}
return ret;
}
Solution 2
二分查找第一个大于等于target的位置和最后一个大于等于target的位置
public int[] searchRange2(int[] nums, int target) {
int[] ret = {-1, -1};
// Find the first item greater than or equal to target
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// Check if left item equals target.
// If not equal, it mean that array nums dont contains item equals to target.
// So return early
if (left == nums.length || nums[left] != target) {
return ret;
}
ret[0] = left;
// Find the last item greater than or equal to target
left = 0;
right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
ret[1] = left - 1;
return ret;
}
Solution 3
二分查找第一个大于等于target的位置和第一个大于等于target + 1的位置
// It is very similar between finding left bound and finding right bound in searchRange2
// (nums[mid] <= target) is equivalent to (nums[mid] < target + 1).
// So the process of finding the last item greater than or equal to target is the process of
// finding the first item greater than target.
public int[] searchRange3(int[] nums, int target) {
int[] ret = {-1, -1};
// Find the first item greater than or equal to target
int position = getPosition(nums, target, 0, nums.length - 1);
// Check if left item equal to target.
// If not equal, it mean that array nums dont contains item equals to target.
// So return early
if (position == nums.length || nums[position] != target) {
return ret;
}
ret[0] = position;
// Find the last item greater than or equal to target
ret[1] = getPosition(nums, target + 1, 0, nums.length - 1) - 1;
return ret;
}
private int getPosition(int[] nums, int target, int left, int right) {
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}