File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Source: https://leetcode.com/problems/merge-k-sorted-lists/
3+ * 풀이방법: 모든 리스트들을 한곳에 넣고 재배치
4+ *
5+ * 시간복잡도: O(NlogN) - 모든 리스트를 순회(N), 정렬(NlogN) 하는데 드는 시간 고려
6+ * 공간복잡도: O(N) - 기존 배열을 저장할 공간만 필요
7+ */
8+
9+ /**
10+ * Definition for singly-linked list.
11+ * class ListNode {
12+ * val: number
13+ * next: ListNode | null
14+ * constructor(val?: number, next?: ListNode | null) {
15+ * this.val = (val===undefined ? 0 : val)
16+ * this.next = (next===undefined ? null : next)
17+ * }
18+ * }
19+ */
20+
21+ function mergeKLists ( lists : Array < ListNode | null > ) : ListNode | null {
22+ if ( ! lists ?. length ) return null ;
23+ let merged = [ ] ;
24+
25+ for ( let i = 0 ; i < lists . length ; i ++ ) {
26+ let cursor = lists [ i ] ;
27+ while ( cursor != null ) {
28+ merged . push ( cursor . val ) ;
29+ cursor = cursor . next ;
30+ }
31+ }
32+ let sorted = merged . sort ( ( a , b ) => ( a < b ? - 1 : 1 ) ) ;
33+ let head = null ;
34+ let tail = null ;
35+
36+ for ( let i = 0 ; i < sorted . length ; i ++ ) {
37+ const node = new ListNode ( sorted [ i ] , null ) ;
38+ if ( head === null ) {
39+ head = node ;
40+ tail = node ;
41+ } else {
42+ tail . next = node ;
43+ tail = node ;
44+ }
45+ }
46+
47+ return head ;
48+ }
You can’t perform that action at this time.
0 commit comments