Skip to content

Commit 939986b

Browse files
committed
add merge k sorted lists solution
1 parent 2dafc41 commit 939986b

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
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

Comments
ย (0)