Skip to content

Commit

Permalink
Time: 8 ms (31.10%), Space: 44.2 MB (17.47%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
saikatkar committed Jan 4, 2022
1 parent 1326a18 commit 0a143dc
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 23-merge-k-sorted-lists/23-merge-k-sorted-lists.java
Original file line number Diff line number Diff line change
@@ -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<ListNode> cmp;
cmp = new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
// TODO Auto-generated method stub
return o1.val-o2.val;
}
};
Queue<ListNode> 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;
}
}

0 comments on commit 0a143dc

Please sign in to comment.