Skip to main content

Search for a Range

描述​

Given a sorted array of integers, 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].

For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

分析​

已经排好了序,用二分查找。

重新实现 lower_bound 和 upper_bound​

# Search for a Range
# 重新实现 lower_bound 和 upper_bound
# 时间复杂度O(logn),空间复杂度O(1)
class Solution:
def searchRange(self, nums: list, target: int) -> list:
lower = self.lower_bound(nums, 0, len(nums), target)
upper = self.upper_bound(nums, 0, len(nums), target)
if lower == len(nums) or nums[lower] != target:
return [-1, -1]
else:
return [lower, upper-1]

def lower_bound(self, A: list, first: int, last: int, target: int) -> int:
while first != last:
mid = first + (last - first) // 2
if target > A[mid]:
first = mid + 1
else:
last = mid
return first

def upper_bound(self, A: list, first: int, last: int, target: int) -> int:
while first != last:
mid = first + (last - first) // 2
if target >= A[mid]: # 与 lower_bound 仅此不同
first = mid + 1
else:
last = mid
return first

相关题目​