File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Constraints:
3
+ - 1 <= nums.length <= 5000
4
+ - -10^4 <= nums[i] <= 10^4
5
+ - All values of nums are unique.
6
+ - nums is an ascending array that is possibly rotated.
7
+ - -10^4 <= target <= 10^4
8
+
9
+ Time Complexity: O(log n)
10
+ - Binary Search -> 매 단계마다 탐색 범위가 절반으로 줄어듦
11
+
12
+ Space Complexity: O(1)
13
+ - 추가 공간을 사용하지 않음
14
+
15
+ 풀이방법:
16
+ 1. Binary Search
17
+ - left와 right 포인터로 탐색 범위 지정
18
+ - mid가 target인지 먼저 확인
19
+
20
+ 2. 정렬된 부분 찾기
21
+ - mid를 기준으로 왼쪽이 정렬되어 있는지 확인
22
+ - 정렬된 부분에서 target이 존재할 수 있는 범위를 파악
23
+
24
+ 3. Target 위치 탐색
25
+ - 왼쪽이 정렬되어 있고 target이 그 범위 안에 있다면 오른쪽 범위를 줄임
26
+ - 그렇지 않다면 왼쪽 범위를 늘림
27
+ - 반대의 경우도 동일한 방법 적용
28
+
29
+ 4. Target을 찾지 못한 경우 -1을 반환함
30
+ """
31
+ class Solution :
32
+ def search (self , nums : List [int ], target : int ) -> int :
33
+ left = 0
34
+ right = len (nums ) - 1
35
+
36
+ while left <= right :
37
+ mid = (left + right ) // 2
38
+
39
+ if nums [mid ] == target :
40
+ return mid
41
+
42
+ if nums [left ] <= nums [mid ]:
43
+ if nums [left ] <= target <= nums [mid ]:
44
+ right = mid - 1
45
+ else :
46
+ left = mid + 1
47
+
48
+ else :
49
+ if nums [mid ] < target <= nums [right ]:
50
+ left = mid + 1
51
+ else :
52
+ right = mid - 1
53
+
54
+ return - 1
55
+
You can’t perform that action at this time.
0 commit comments