Merge k Sorted Lists
Thoughts
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
pq.offer(lists[i]);
}
}
ListNode dummy = new ListNode(0), node = dummy;
while (!pq.isEmpty()) {
ListNode newNode = pq.poll();
node.next = newNode;
node = newNode;
if (newNode.next != null) {
pq.offer(newNode.next);
}
}
return dummy.next;
}
}Aanlysis
Last updated