1+ import java .util .PriorityQueue ;
2+
3+ /**
4+ * Definition for singly-linked list.
5+ * public class ListNode {
6+ * int val;
7+ * ListNode next;
8+ * ListNode() {}
9+ * ListNode(int val) { this.val = val; }
10+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
11+ * }
12+ */
13+ class Solution {
14+
15+ // ์ฐ์ ์์ ํ๋ฅผ ํ์ฉ
16+ // ์๊ฐ๋ณต์ก๋: O(N log k)
17+ public ListNode mergeKLists (ListNode [] lists ) {
18+ if (lists == null || lists .length == 0 ) {
19+ return null ;
20+ }
21+
22+ // ์ฐ์ ์์ ํ ์์ฑ
23+ PriorityQueue <ListNode > pqueue = new PriorityQueue <>(
24+ (a , b ) -> Integer .compare (a .val , b .val )
25+ );
26+
27+ // ์ฒซ๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐ์ ์์ ํ์ ์ฝ์
28+ for (ListNode node : lists ) {
29+ if (node != null ) {
30+ pqueue .offer (node );
31+ }
32+ }
33+
34+ ListNode temp = new ListNode (-1 );
35+ ListNode current = temp ;
36+
37+ // ๊บผ๋ธ ๋
ธ๋์ ๋ค์๋
ธ๋๊ฐ ์์ผ๋ฉด ํ์ ๋ฃ๋ ๊ฒ์ ๋ฐ๋ณต
38+ while (!pqueue .isEmpty ()) {
39+ ListNode node = pqueue .poll ();
40+ current .next = node ;
41+ current = current .next ;
42+
43+ if (node .next != null ) {
44+ pqueue .offer (node .next );
45+ }
46+ }
47+
48+ return temp .next ;
49+ }
50+
51+ // ์๊ฐ๋ณต์ก๋: O(N log K)
52+ // public ListNode mergeKLists(ListNode[] lists) {
53+ // if (lists == null || lists.length == 0) {
54+ // return null;
55+ // }
56+
57+ // return mergeKLists(lists, 0, lists.length - 1);
58+
59+ // }
60+
61+ // ๋จ๊ณ๋ง๋ค left, right๋ก ๋๋์ด ๋ฆฌ์คํธ ๋ณํฉ
62+ // private ListNode mergeKLists(ListNode[] lists, int start, int end) {
63+
64+ // if (start == end) {
65+ // return lists[start];
66+ // }
67+
68+ // int mid = start + (end - start) / 2;
69+
70+ // ListNode left = mergeKLists(lists, start, mid);
71+ // ListNode right = mergeKLists(lists, mid + 1, end);
72+
73+ // return mergeLists(left, right);
74+ // }
75+
76+ // ๋ ๊ฐ์ ๋
ธ๋์ ๋ํด ๋
ธ๋์ ๊ฐ ๋น๊ตํ์ฌ ListNode์ ์ฐ๊ฒฐํ์ฌ ํ๋๋ก ๋ณํฉ
77+ // private ListNode mergeLists(ListNode node1, ListNode node2) {
78+ // ListNode temp = new ListNode(-1);
79+ // ListNode current = temp;
80+
81+ // while (node1 != null && node2 != null) {
82+ // if (node1.val < node2.val) {
83+ // current.next = node1;
84+ // node1 = node1.next;
85+ // } else {
86+ // current.next = node2;
87+ // node2 = node2.next;
88+ // }
89+ // current = current.next;
90+ // }
91+
92+ // if (node1 != null) current.next = node1;
93+ // if (node2 != null) current.next = node2;
94+
95+ // return temp.next;
96+ // }
97+
98+ }
0 commit comments