Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
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]
LeetCode:链接
首先要弄懂自己写的二分法:链接
方法一:使用二分法找到目标值,然后以此目标值为中心,向左右两边扩展,但要考虑边界的情况。或是找到nums[mid]==target,然后从区间[low、high]的边缘向内缩小,来确定范围。
方法二(最优解):同样使用二分法,先找到左端点,然后继续使用二分法去探查右端点。
一定要注意,查找左端点返回的是左指针,查找右端点返回的是右指针!
如果找不到,比如12没有,最终end是9, start是10;比如0没有,最终start是0, end是-1!所有最终二分法的start和end都回归到这种结果!!!!
class Solution:
def searchRange(self, nums, target):
def binarySearchLeft(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target > nums[mid]:
low = mid + 1
else:
high = mid - 1
# 左边界返回的是low
return low
def binarySearchRight(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target >= nums[mid]:
low = mid + 1
else:
high = mid - 1
# 找右边界返回的是high
return high
left, right = binarySearchLeft(nums, target), binarySearchRight(nums, target)
return (left, right) if left <= right else [-1, -1]