File tree 3 files changed +113
-0
lines changed
find-minimum-in-rotated-sorted-array 3 files changed +113
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 정렬된 배열에서 최소값 찾기
3
+ * 알고리즘 복잡도
4
+ * - 시간 복잡도: O(logn)
5
+ * - 공간 복잡도: O(1)
6
+ * @param nums
7
+ */
8
+ function findMin ( nums : number [ ] ) : number {
9
+ // 풀이 1 - sort() 사용
10
+ // 시간 복잡도: O(nlogn) / 공간 복잡도: O(1)
11
+ // nums.sort((a, b) => a - b)
12
+ // return nums[0]
13
+
14
+ // 풀이 2 - 배열이 정렬되어 있음을 활용한 풀이
15
+ // 시간 복잡도: O(n) / 공간 복잡도: O(1)
16
+ // let min = nums[0];
17
+ // for(let i = 1; i < nums.length; i++) {
18
+ // console.log(nums[i])
19
+ // min = Math.min(nums[i], min)
20
+ // }
21
+ // return min
22
+
23
+ // 이분 탐색법 활용
24
+ // 절반씩 잘라서 nums[n-1] > nums[n] 의 지점을 찾는다
25
+ let low = 0 ;
26
+ let high = nums . length - 1 ;
27
+ while ( low < high ) {
28
+ let mid = low + Math . floor ( ( high - low ) / 2 ) ;
29
+
30
+ if ( nums [ mid ] > nums [ high ] ) {
31
+ low = mid + 1 ;
32
+ } else {
33
+ high = mid ;
34
+ }
35
+ }
36
+ return nums [ low ]
37
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * val: number
5
+ * next: ListNode | null
6
+ * constructor(val?: number, next?: ListNode | null) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.next = (next===undefined ? null : next)
9
+ * }
10
+ * }
11
+ */
12
+ /**
13
+ * 순환되는 링크드 리스트 찾기
14
+ * 알고리즘 복잡도
15
+ * - 시간 복잡도: O(n)
16
+ * - 공간 복잡도: O(1)
17
+ * @param head
18
+ */
19
+ function hasCycle ( head : ListNode | null ) : boolean {
20
+ // 1. set을 이용한 풀이
21
+ // 시간 복잡도: O(n) , 공간 복잡도: O(n)
22
+ // let set = new Set();
23
+ // while(head !== null) {
24
+ // // set에 이미 존재하는지 확인
25
+ // if(set.has(head)) return true
26
+ // set.add(head)
27
+ // head = head.next
28
+ // }
29
+
30
+ // 2. 토끼와 거북이 알고리즘
31
+ // 포인터를 2개 이동하는 방법
32
+ let slow = head
33
+ let fast = head
34
+
35
+ while ( fast ?. next ) {
36
+ slow = slow . next
37
+ fast = fast . next . next
38
+
39
+ if ( slow === fast ) {
40
+ return true
41
+ }
42
+ }
43
+
44
+ return false
45
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 최대 부분 곱 구하기
3
+ * 알고리즘 복잡도
4
+ * - 시간 복잡도: O(n)
5
+ * - 공간 복잡도: O(1)
6
+ * @param nums
7
+ */
8
+ function maxProduct ( nums : number [ ] ) : number {
9
+ if ( nums . length === 1 ) return nums [ 0 ]
10
+
11
+ let max = nums [ 0 ]
12
+ let currMax = nums [ 0 ]
13
+ let currMin = nums [ 0 ]
14
+
15
+ for ( let i = 1 ; i < nums . length ; i ++ ) {
16
+ const temp = currMax ;
17
+
18
+ currMax = Math . max (
19
+ nums [ i ] , temp * nums [ i ] , currMin * nums [ i ]
20
+ )
21
+
22
+ currMin = Math . min (
23
+ nums [ i ] , temp * nums [ i ] , currMin * nums [ i ]
24
+ )
25
+
26
+ max = Math . max ( max , currMax ) ;
27
+ }
28
+
29
+ return max ;
30
+
31
+ }
You can’t perform that action at this time.
0 commit comments