File tree 1 file changed +71
-3
lines changed
find-minimum-in-rotated-sorted-array
1 file changed +71
-3
lines changed Original file line number Diff line number Diff line change 1
1
"""
2
2
[문제풀이]
3
3
# Inputs
4
-
4
+ - sorted rotated array : nums
5
+ - nums안의 요소는 unique
5
6
# Outputs
6
-
7
+ - 배열의 가장 작은 값 Return
7
8
# Constraints
8
-
9
+ - O(logN) 시간대로 풀어야함
10
+ - n == nums.length
11
+ - 1 <= n <= 5000
12
+ - -5000 <= nums[i] <= 5000
13
+ - All the integers of nums are unique.
14
+ - nums is sorted and rotated between 1 and n times.
9
15
# Ideas
16
+ 그냥 정렬은 O(NlogN) 이어서 불가능
17
+ rotate : 맨 끝의 요소가 맨 처음으로 옴
18
+ 이진탐색이 O(logN) 이긴한데..->하지만, 이진탐색은 정렬된 배열에서만 사용가능
19
+ 그리고, 이 문제에선 아닌 것 같다
20
+
21
+ 끝의 원소를 빼서 stack에 append -> 모두 o(1)
22
+
23
+ 회전되어 있는 배열의 특성을 활용하여
24
+ -> 끝의 원소 빼고, 그걸 stack 에 넣기
25
+ -> 그리고 stack의 맨 끝 원소보다 nums의 끝 원소가 더 클때
26
+ stack[-1] 이 정답
27
+ -> 근데 이건 o(n) 아닌가??
28
+
29
+ 우선 내 풀이 정답
30
+ 해설 참고
31
+ -> 내 풀이는 O(n) 이다.. O(logN) 풀이가 필요
32
+ 이분탐색 응용문제이다
10
33
11
34
[회고]
12
35
13
36
"""
14
37
38
+ # 내 풀이
39
+ from collections import deque
40
+
41
+
42
+ class Solution :
43
+ def findMin (self , nums : List [int ]) -> int :
44
+
45
+ if len (nums ) == 1 :
46
+ return nums [0 ]
47
+
48
+ nums = deque (nums )
49
+
50
+ st = []
51
+ ret = 0
52
+
53
+ while nums :
54
+ num = nums .pop ()
55
+
56
+ if not nums :
57
+ ret = num
58
+ break
59
+
60
+ if num < nums [- 1 ]:
61
+ ret = num
62
+ break
63
+
64
+ return ret
65
+
66
+ # 해설
67
+ class Solution :
68
+ def findMin (self , nums : List [int ]) -> int :
69
+
70
+ left , right = 1 , len (nums ) - 1
71
+
72
+ while left <= right :
73
+ mid = (left + right ) // 2
74
+ if nums [mid - 1 ] > nums [mid ]:
75
+ return nums [mid ]
76
+ if nums [0 ] < nums [mid ]:
77
+ left = mid + 1
78
+ else :
79
+ right = mid - 1
80
+
81
+ return nums [0 ]
82
+
15
83
You can’t perform that action at this time.
0 commit comments