File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ 1) binary search 로 pivot 찾아 2번 binary search 하기
3
+ Time: O(log(n))
4
+ Space: O(1)
5
+ """
6
+
7
+
8
+ class Solution :
9
+ def search (self , nums : List [int ], target : int ) -> int :
10
+
11
+ def find_pivot ():
12
+ low , high = 0 , len (nums ) - 1
13
+ while low <= high :
14
+ mid = (low + high ) // 2
15
+ if mid > 0 and nums [mid - 1 ] >= nums [mid ]:
16
+ return mid
17
+ if nums [0 ] <= nums [mid ]:
18
+ low = mid + 1
19
+ else :
20
+ high = mid - 1
21
+ return 0
22
+
23
+ def binary_search (low , high ):
24
+ while low <= high :
25
+ mid = (low + high ) // 2
26
+ if nums [mid ] == target :
27
+ return mid
28
+ if nums [mid ] < target :
29
+ low = mid + 1
30
+ else :
31
+ high = mid - 1
32
+ return - 1
33
+
34
+ pivot = find_pivot ()
35
+
36
+ idx = binary_search (0 , pivot - 1 )
37
+ return idx if idx > - 1 else binary_search (pivot , len (nums ) - 1 )
38
+
39
+
40
+ """
41
+ 2) binary search
42
+ left sorted case
43
+ 4 5 6 7 0 1 2 3
44
+ m
45
+ left target case
46
+ right target case
47
+
48
+ right sorted case
49
+ 6 7 0 1 2 3 4 5
50
+ m
51
+ left target case
52
+ right target case
53
+ Time: O(log(n))
54
+ Space: O(1)
55
+ """
56
+
57
+
58
+ class Solution :
59
+ def search (self , nums : List [int ], target : int ) -> int :
60
+
61
+ low , high = 0 , len (nums ) - 1
62
+ while low <= high :
63
+ mid = (low + high ) // 2
64
+ if target == nums [mid ]:
65
+ return mid
66
+
67
+ if nums [low ] <= nums [mid ]:
68
+ if nums [low ] <= target <= nums [mid ]:
69
+ high = mid - 1
70
+ else :
71
+ low = mid + 1
72
+ else :
73
+ if nums [mid ] <= target <= nums [high ]:
74
+ low = mid + 1
75
+ else :
76
+ high = mid - 1
77
+ return - 1
You can’t perform that action at this time.
0 commit comments