File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ class ListNode {
2+ val : number ;
3+ next : ListNode | null ;
4+ constructor ( val ?: number , next ?: ListNode | null ) {
5+ this . val = val === undefined ? 0 : val ;
6+ this . next = next === undefined ? null : next ;
7+ }
8+ }
9+
10+ /**
11+ * @link https://leetcode.com/problems/merge-k-sorted-lists/description/
12+ *
13+ * 접근 방법 :
14+ * - 리스트를 배열에 넣고, 최소값을 가진 노드 찾기
15+ * - 최소값 노드를 더미 노드에 연결한 뒤 제거하고, 최소값 노드의 다음 노드를 다시 배열에 추가하기
16+ * - 배열 길이가 0이 될 때까지 반복하기
17+ *
18+ * 시간복잡도 : O(n * k)
19+ * - n = 총 노드의 개수
20+ * - k = 리스트의 개수
21+ * - 최소값 찾고, 최소값 제거하는 로직: O(k)
22+ * - 위의 연산을 총 n번 실행
23+ *
24+ * 공간복잡도 : O(k)
25+ * - k = 리스트 개수
26+ * - minList 배열의 크기가 최대 K개까지 유지
27+ *
28+ */
29+
30+ function mergeKLists ( lists : Array < ListNode | null > ) : ListNode | null {
31+ const minList : ListNode [ ] = [ ] ;
32+
33+ for ( const list of lists ) {
34+ if ( list !== null ) minList . push ( list ) ;
35+ }
36+
37+ const dummy = new ListNode ( ) ;
38+ let tail = dummy ;
39+
40+ while ( minList . length > 0 ) {
41+ const minIndex = getMinIndex ( minList ) ;
42+ const minNode = minList . splice ( minIndex , 1 ) [ 0 ] ;
43+
44+ tail . next = minNode ;
45+ tail = tail . next ;
46+
47+ if ( minNode . next ) minList . push ( minNode . next ) ;
48+ }
49+
50+ return dummy . next ;
51+ }
52+
53+ function getMinIndex ( nodes : ListNode [ ] ) : number {
54+ let minIndex = 0 ;
55+
56+ for ( let i = 1 ; i < nodes . length ; i ++ ) {
57+ if ( nodes [ i ] . val < nodes [ minIndex ] . val ) minIndex = i ;
58+ }
59+
60+ return minIndex ;
61+ }
You can’t perform that action at this time.
0 commit comments