File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * function ListNode(val, next) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.next = (next===undefined ? null : next)
6+ * }
7+ */
8+ /**
9+ * @param {ListNode[] } lists
10+ * @return {ListNode }
11+ */
12+ var mergeKLists = function ( lists ) {
13+ const arr = [ ] ;
14+
15+ for ( let i = 0 ; i < lists . length ; i ++ ) {
16+ let list = lists [ i ] ;
17+
18+ while ( list ) {
19+ arr . push ( list . val ) ;
20+ list = list . next ;
21+ }
22+ }
23+
24+ if ( ! arr . length ) {
25+ return null ;
26+ }
27+
28+ arr . sort ( ( a , b ) => a - b ) ;
29+
30+ const first = new ListNode ( arr [ 0 ] ) ;
31+
32+ let node = first ;
33+
34+ for ( let j = 1 ; j < arr . length ; j ++ ) {
35+ const next = new ListNode ( arr [ j ] ) ;
36+ node . next = next ;
37+ node = next ;
38+ }
39+
40+ return first ;
41+ } ;
42+
43+ // 시간복잡도 -> for문 이후 sort 이후 for문을 수행하며 이는 O(n) + O(nlogn) + O(n)이므로 O(nlogn)가 시간복잡도가 된다
44+ // 공간복잡도 -> lists의 노드 수 만큼 길이가 결정되므로 0(n)
You can’t perform that action at this time.
0 commit comments