二分法找左右边界,引入 bisect 模块,bisect_left 求出左边界 l(表示有几个值 < target), bisect_right 求出右边界 r(表示有几个值 <= target), 结果中是该值左侧和右侧的索引, 返回 [l, r - 1]
import bisect
class Solution:
def searchRange(self , nums: List[int], target: int) -> List[int]:
# write code here
if target not in nums: return [-1, -1]
l, r = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target) - 1
return [l, r]