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
26
27
28
29
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if nums == []:
return [-1, -1]
# 找最左
left = 0
right = len(nums) - 1
while left <= right:
half = left + (right - left) // 2
if nums[half] >= target:
right = half - 1
else:
left = half + 1
print(left,right)
target_left = left if (left!=len(nums) and nums[left] == target) else -1
print(target_left)
# 找最右
left = 0
right = len(nums) - 1
while left <= right:
half = left + (right - left) // 2
if nums[half] <= target:
left = half + 1
else:
right = half - 1
print(left,right)
target_right = right if (right!=-1 and nums[right] == target) else -1
print(target_right)
return [target_left,target_right]