0034. Find First and Last Position of Element in Sorted Array - kumaeki/LeetCode GitHub Wiki
34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
Follow up: Could you write an algorithm with O(log n) runtime complexity?
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
Constraints:
- 0 <= nums.length <= 105
- -109 <= nums[i] <= 109
- nums is a non-decreasing array.
- -109 <= target <= 109
解法1
普通的BinarySearch 是找到相等的就返回结果. 但是本题中是要找到起始位置和终止位置.
所以, 分两步来做, 一次找到最左端, 一次找到最右端.
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1, -1};
if(nums.length == 0)
return res;
// 找到左边界
int left = 0, right = nums.length - 1;
while(left <= right){
int mid = (left + right) / 2;
// 目标值小于等于当前值时, 继续向左侧缩小范围
if(target <= nums[mid])
right = mid - 1;
else
left = mid + 1;
}
// 如果left超过边界,或者找到的值不等于目标值,说明目标值在数组中不存在
if(left >= nums.length || nums[left] != target)
return res;
res[0] = left;
// 找到右边界
left = 0;
right = nums.length - 1;
while(left <= right){
int mid = (left + right) / 2;
if(target < nums[mid])
right = mid - 1;
// 目标值大于等于当前值时,继续向右侧缩小范围
else
left = mid + 1;
}
res[1] = right;
return res;
}
}