File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 33. Search in Rotated Sorted Array
3
+
4
+ binary search + condition check
5
+
6
+ μ΄μ§ νμ μ€, μΌμͺ½μ΄ μ λ ¬λμμ λ
7
+ - νκ²μ΄ μ λ ¬λ μΌμͺ½μ μλ κ²½μ°, μΌμͺ½ νμ (leftλΆν° mid - 1 μ¬μ΄μμ νκ²μ νμ)
8
+ - νκ²μ΄ μ λ ¬λ μΌμͺ½μ μμ κ²½μ°, μ€λ₯Έμͺ½ νμ (mid + 1λΆν° right μ¬μ΄μμ νκ²μ νμ)
9
+
10
+ μ΄μ§ νμ μ€, μ€λ₯Έμͺ½μ΄ μ λ ¬λμμ λ
11
+ - νκ²μ΄ μ λ ¬λ μ€λ₯Έμͺ½μ μλ κ²½μ°, μ€λ₯Έμͺ½ νμ (mid + 1λΆν° right μ¬μ΄μμ νκ²μ νμ)
12
+ - νκ²μ΄ μ λ ¬λ μ€λ₯Έμͺ½μ μμ κ²½μ°, μΌμͺ½ νμ (leftλΆν° mid - 1 μ¬μ΄μμ νκ²μ νμ)
13
+
14
+ ## TC: O(log n)
15
+
16
+ binary search
17
+
18
+ ## SC: O(1)
19
+
20
+ no extra space
21
+
22
+ '''
23
+ class Solution :
24
+ def search (self , nums : List [int ], target : int ) -> int :
25
+ left = 0
26
+ right = len (nums ) - 1
27
+
28
+ while left <= right :
29
+ mid = left + (right - left ) // 2
30
+
31
+ if nums [mid ] == target :
32
+ return mid
33
+
34
+ if nums [left ] <= nums [mid ]: # is_left_sorted
35
+ if nums [left ] <= target < nums [mid ]: # is_target_left
36
+ right = mid - 1
37
+ else :
38
+ left = mid + 1
39
+ else :
40
+ if nums [mid ] < target <= nums [right ]: # is_target_right
41
+ left = mid + 1
42
+ else :
43
+ right = mid - 1
44
+
45
+ return - 1
You canβt perform that action at this time.
0 commit comments