https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
题目没什么好说的,比较纯粹,权当是记下来二分查找的模板了。bisect_left和bisect_right


个人解答

  1. class Solution:
  2. def searchRange(self, nums: List[int], target: int) -> List[int]:
  3. def bisect_left(m, x):
  4. l, r = 0, len(m)
  5. while l < r:
  6. mid = (l + r) // 2
  7. if m[mid] >= x:
  8. r = mid
  9. else:
  10. l = mid + 1
  11. return l
  12. def bisect_right(m, x):
  13. l, r = 0, len(m)
  14. while l < r:
  15. mid = (l + r) // 2
  16. if m[mid] <= x:
  17. l = mid + 1
  18. else:
  19. r = mid
  20. return l
  21. l = bisect_left(nums, target)
  22. r = bisect_right(nums, target) - 1
  23. if l == len(nums) or nums[l] != target:
  24. l = -1
  25. if r < 0 or nums[r] != target:
  26. r = -1
  27. return [l, r]

题目分析

二分查找的两个形式,python标准库的形式挺好的,可以记住,也比较统一。