力扣 34. 在排序数组中查找元素的第一个和最后一个位置

左右二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def searchRange(nums, target):
# 左右二分
def search_left(l, r, t):
while l < r:
m = l + r >> 1
if nums[m] < t:
l = m + 1
else:
r = m
return l

def search_right(l, r, t):
while l < r:
m = l + r + 1 >> 1
if nums[m] > t:
r = m - 1
else:
l = m
return l
if not nums: return [-1, -1]
nums_len = len(nums) - 1
left = search_left(0, nums_len, target)
right = search_right(0, nums_len, target)

return [left, right] if nums[left] == target and nums[right] == target else [-1, -1]
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信