File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ """
4
+ https://leetcode.com/problems/search-in-rotated-sorted-array/solutions/
5
+
6
+ 문제: 회전된 오름차순 정렬된 배열 nums에서 target 값의 인덱스를 반환하라.
7
+
8
+ Idea: 이진 탐색 패턴 사용
9
+
10
+ TC: O(logN)
11
+ SC: O(1)
12
+ """
13
+
14
+ class Solution :
15
+ def search (self , nums : List [int ], target : int ) -> int :
16
+ left , right = 0 , len (nums ) - 1
17
+
18
+ while left <= right :
19
+ mid = (left + right ) // 2
20
+
21
+ if nums [mid ] == target :
22
+ return mid
23
+
24
+ # 왼쪽이 정렬된 경우
25
+ if nums [left ] <= nums [mid ]:
26
+ # target이 정해진 구간에 있는 경우
27
+ if nums [left ] <= target < nums [mid ]:
28
+ # 왼쪽만 탐색하도록 right를 줄임
29
+ right = mid - 1
30
+ # 아니라면 오른쪽으로 범위를 옮김
31
+ else :
32
+ left = mid + 1
33
+ # 오른쪽이 정렬된 경우
34
+ else :
35
+ # target이 정해진 구간에 있는 경우
36
+ if nums [mid ] < target <= nums [right ]:
37
+ # 오른쪽만 탐색하도록 left를 늘림
38
+ left = mid + 1
39
+ # 아니라면 왼쪽으로 범위를 옮김
40
+ else :
41
+ right = mid - 1
42
+ return - 1
You can’t perform that action at this time.
0 commit comments