https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
题目没什么好说的,比较纯粹,权当是记下来二分查找的模板了。bisect_left和bisect_right
个人解答
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def bisect_left(m, x):
l, r = 0, len(m)
while l < r:
mid = (l + r) // 2
if m[mid] >= x:
r = mid
else:
l = mid + 1
return l
def bisect_right(m, x):
l, r = 0, len(m)
while l < r:
mid = (l + r) // 2
if m[mid] <= x:
l = mid + 1
else:
r = mid
return l
l = bisect_left(nums, target)
r = bisect_right(nums, target) - 1
if l == len(nums) or nums[l] != target:
l = -1
if r < 0 or nums[r] != target:
r = -1
return [l, r]
题目分析
二分查找的两个形式,python标准库的形式挺好的,可以记住,也比较统一。