Skip to content

Commit

Permalink
Merge K Sorted Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyKim9401 committed Oct 18, 2024
1 parent 1c60fed commit 19c3560
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions merge-k-sorted-lists/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// TC: O(n * log m)
// m -> the number of the lists, n -> the number of node
// SC: O(m)
// m -> the number of the lists (max m)
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;

PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);

for (ListNode node : lists) {
if (node != null) pq.offer(node);
}

ListNode dummy = new ListNode(0);
ListNode current = dummy;

while (!pq.isEmpty()) {
ListNode minNode = pq.poll();
current.next = minNode;
current = current.next;

if (minNode.next != null) {
pq.offer(minNode.next);
}
}

return dummy.next;
}
}

0 comments on commit 19c3560

Please sign in to comment.