- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch_insert_position.py
31 lines (25 loc) · 1.07 KB
/
search_insert_position.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
classSolution:
# main idea:
# use 'binary_search' for a 'sorted array'
# be careful: If not, return the index where it would be 'if it were inserted' in order
defmy_binary_search(self, nums, target, begin, end):
# calculate the mid (by using 'plus')
mid= (end+begin) //2
print(mid)
# set the 'stopping' condition
ifbegin>end:
# be careful: return the 'Insert Position' => return 'begin'
returnbegin
elifnums[mid] ==target:
returnmid
# the recursion of binary search
elifnums[mid] <target:
returnself.my_binary_search(nums, target, mid+1, end)
elifnums[mid] >target:
returnself.my_binary_search(nums, target, begin, mid-1)
#else:
# return 0
defsearchInsert(self, nums: List[int], target: int) ->int:
# return the 'index'
index=self.my_binary_search(nums, target, 0, len(nums)-1)
returnindex