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