diff --git a/merge-k-sorted-lists/TonyKim9401.java b/merge-k-sorted-lists/TonyKim9401.java new file mode 100644 index 000000000..ac513085c --- /dev/null +++ b/merge-k-sorted-lists/TonyKim9401.java @@ -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 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; + } +}