Skip to content

Commit 19c3560

Browse files
committed
Merge K Sorted Lists
1 parent 1c60fed commit 19c3560

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

merge-k-sorted-lists/TonyKim9401.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// TC: O(n * log m)
2+
// m -> the number of the lists, n -> the number of node
3+
// SC: O(m)
4+
// m -> the number of the lists (max m)
5+
class Solution {
6+
public ListNode mergeKLists(ListNode[] lists) {
7+
if (lists == null || lists.length == 0) return null;
8+
9+
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
10+
11+
for (ListNode node : lists) {
12+
if (node != null) pq.offer(node);
13+
}
14+
15+
ListNode dummy = new ListNode(0);
16+
ListNode current = dummy;
17+
18+
while (!pq.isEmpty()) {
19+
ListNode minNode = pq.poll();
20+
current.next = minNode;
21+
current = current.next;
22+
23+
if (minNode.next != null) {
24+
pq.offer(minNode.next);
25+
}
26+
}
27+
28+
return dummy.next;
29+
}
30+
}

0 commit comments

Comments
 (0)