题目
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must 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 <= 10^5
-10^9 <= nums[i] <= 10^9
nums
is a non-decreasing array.-10^9 <= target <= 10^9
思路
两次二分查找,第一次查找目标数字的左边界,第二次则查找右边界。
代码
python版本:
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
l, r = 0, len(nums)
res = [-1, -1]
while l < r:
mid = (l+r)//2
if nums[mid] < target:
l = mid+1
else:
r = mid
if l >= 0 and l < len(nums) and nums[l] == target:
res[0] = l
r = len(nums)
while l < r:
mid = (l+r)//2
if nums[mid] > target:
r = mid
else:
l = mid+1
if l-1 >= 0 and l-1 < len(nums) and nums[l-1] == target:
res[1] = l-1
return res