-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path34.py
64 lines (59 loc) · 2.17 KB
/
34.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
__________________________________________________________________________________________________
sample 28 ms submission
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums)==0: return [-1,-1]
lbound, rbound = -1,-1
# for the left one
left, right = 0, len(nums)-1
while left+1<right:
mid = left + (right-left)//2
if nums[mid] == target:
right = mid
elif nums[mid] < target:
left = mid
else: right = mid
if nums[left] == target:
lbound = left
elif nums[right] == target:
lbound = right
else: return [-1,-1]
#for the right one
left, right = 0, len(nums)-1
while left+1<right:
mid = left + (right-left)//2
if nums[mid] == target:
left = mid # 这里不一样
elif nums[mid] < target:
left = mid
else: right = mid
if nums[right] == target: #这里不一样,先right,
rbound = right
elif nums[left] == target:
rbound = left
else: return [-1,-1]
return [lbound, rbound]
__________________________________________________________________________________________________
sample 13452 kb submission
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
try:
fp = nums.index(target)
except ValueError:
return [-1, -1]
for i in range(len(nums)-1, fp, -1):
if nums[i] == target:
return [fp, i]
else:
return [fp, fp]
def bs_leftmost(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo+hi) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
hi = mid
else:
low = mid
__________________________________________________________________________________________________