Skip to content

Commit 7701709

Browse files
committed
update binary search
1 parent 13578b4 commit 7701709

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# very similar to the basic binary search
2+
# the only difference is the target value can repeat n times in the list, so once you locate the mid that eaqual to the target number
3+
# you need two pointers from the mid to find the left and right boundary index that gives you the same value as the target
4+
5+
class Solution:
6+
def searchRange(self, nums: List[int], target: int) -> List[int]:
7+
l = 0
8+
r = len(nums)-1
9+
while l <= r:
10+
mid = l +(r-l)//2
11+
if nums[mid] == target:
12+
l = mid
13+
r = mid
14+
15+
while l >=0 and nums[l] == target :
16+
l -= 1
17+
18+
while r <=len(nums)-1 and nums[r] == target :
19+
r +=1
20+
21+
return [l+1,r-1]
22+
elif nums[mid] > target:
23+
r = mid -1
24+
elif nums[mid] < target:
25+
l = mid + 1
26+
return [-1,-1]

0 commit comments

Comments
 (0)