Skip to content

Commit eedadad

Browse files
committed
search-in-rotated-sorted-arrary solution (py)
1 parent 8178eb7 commit eedadad

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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

0 commit comments

Comments
 (0)