Skip to content

Commit ea7e374

Browse files
Chris WuChris Wu
authored andcommitted
search-insert-position.py
1 parent c53be1b commit ea7e374

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

problems/search-insert-position.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
We use the concept of binary search to find the index.
3+
`l` and `r` indicates the range we are going to search.
4+
5+
First, check if the target is out of range. [0]
6+
Second, check if the target is the same at `l` or `r`. [1]
7+
Third, we use a pivot to navigate our `l` and `r`. [2]
8+
* If the value on the pivot is larger then the target, we search the left-half.
9+
* If the value on the pivot is smaller then the target, we search the right-half.
10+
Repeat those three steps.
11+
12+
Last, If we could not find the target, the `l` and `r` will collapse (`l==r`) and it will be the value that is closet to the target. [4]
13+
14+
One thing to keep in mind, if we decided to insert to the right of the index `k`, the output will be `k+1`.
15+
If we decided to insert to the left of the index `k`, the output will be `k`, because we shift all the others to the right.
16+
17+
Time complexity is O(LogN), space complexity is O(1).
18+
"""
19+
class Solution(object):
20+
def searchInsert(self, nums, target):
21+
if nums is None or len(nums)==0: return 0
22+
l = 0
23+
r = len(nums)-1
24+
25+
while l<r:
26+
#[0]
27+
if nums[l]>target: return l
28+
if nums[r]<target: return r+1
29+
30+
#[1]
31+
if nums[l]==target: return l
32+
if nums[r]==target: return r
33+
34+
#[2]
35+
p = (l+r)/2
36+
if nums[p]==target:
37+
return p
38+
elif nums[p]>target:
39+
r = p-1
40+
else:
41+
l = p+1
42+
43+
#[4]
44+
if nums[l]==target:
45+
return l
46+
elif nums[l]>target:
47+
return l
48+
else:
49+
return l+1

0 commit comments

Comments
 (0)