From 0a143dc74387fd140269d89a9aaab60dc4cf4d59 Mon Sep 17 00:00:00 2001 From: Saikat Kar Date: Tue, 4 Jan 2022 23:49:14 +0530 Subject: [PATCH] Time: 8 ms (31.10%), Space: 44.2 MB (17.47%) - LeetHub --- .../23-merge-k-sorted-lists.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 23-merge-k-sorted-lists/23-merge-k-sorted-lists.java diff --git a/23-merge-k-sorted-lists/23-merge-k-sorted-lists.java b/23-merge-k-sorted-lists/23-merge-k-sorted-lists.java new file mode 100644 index 0000000..434533a --- /dev/null +++ b/23-merge-k-sorted-lists/23-merge-k-sorted-lists.java @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + Comparator cmp; + cmp = new Comparator() { + @Override + public int compare(ListNode o1, ListNode o2) { + // TODO Auto-generated method stub + return o1.val-o2.val; + } + }; + Queue pq = new PriorityQueue<>(cmp); + ListNode mergedHead = new ListNode(); + ListNode result = mergedHead; + for (ListNode ln : lists) { + if(ln != null) { + pq.add(ln); + } + } + while (!pq.isEmpty()) { + ListNode min = pq.poll(); + mergedHead.next = min; + mergedHead = mergedHead.next; + if (min.next != null) { + min = min.next; + pq.add(min); + } + } + return result.next; + } +} \ No newline at end of file