File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments