-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path34.find-first-and-last-position-of-element-in-sorted-array.py
More file actions
44 lines (36 loc) · 1.41 KB
/
34.find-first-and-last-position-of-element-in-sorted-array.py
File metadata and controls
44 lines (36 loc) · 1.41 KB
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
class Solution:
sidx = -1
eidx = -1
def searchRange(self, nums: List[int], target: int) -> List[int]:
self.binary_search(nums,0,len(nums)-1, target)
return [self.sidx, self.eidx]
def binary_search(self, num, start, end, target):
while start <= end:
mid = start + (end-start) // 2
if num[mid] == target:
if mid == 0:
self.sidx = mid
if self.eidx != -1:
return
elif num[mid-1] != target:
self.sidx = mid
if self.eidx != -1:
return
else:
self.binary_search(num,start, mid-1, target)
if mid == len(num)-1:
self.eidx = mid
if self.sidx != -1:
return
elif num[mid+1] != target:
# print("End", mid)
self.eidx = mid
if self.sidx != -1:
return
else:
self.binary_search(num,mid+1, end, target)
if num[mid] > target:
end = mid-1
else:
start = mid+1
return