File tree 1 file changed +38
-0
lines changed
find-minimum-in-rotated-sorted-array
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ // time: O(n), space: O(1)
2
+ // 투포인터로 양 끝에서 하나씩 줄여가며 가장 작은값 찾아 반환하기.
3
+ class Solution {
4
+ func findMin( _ nums: [ Int ] ) -> Int {
5
+ guard nums. count != 1 else { return nums. first! }
6
+
7
+ var answer = Int . max
8
+ var left = 0
9
+ var right = nums. count
10
+
11
+ while right - left > 0 {
12
+ let temp = min ( nums [ left] , nums [ right - 1 ] )
13
+ answer = min ( answer, temp)
14
+ left += 1
15
+ right -= 1
16
+ }
17
+
18
+ return answer
19
+ }
20
+ }
21
+ // time: O(log n), space: O(1)
22
+ // 중간 값과 오른쪽 값중 가장 작은쪽을 기준으로 잘라가며 탐색함 (이진 탐색)
23
+ class Solution {
24
+ func findMin( _ nums: [ Int ] ) -> Int {
25
+ guard nums. count != 1 else { return nums. first! }
26
+
27
+ var left = 0
28
+ var right = nums. count - 1
29
+
30
+ while left < right {
31
+ let mid = ( left + right) / 2
32
+ if nums [ mid] < nums [ right] { right = mid }
33
+ else { left = mid + 1 }
34
+ }
35
+ return nums [ right]
36
+ }
37
+ }
38
+
You can’t perform that action at this time.
0 commit comments