23. Merge k Sorted Lists
Merge_k_sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[1->4->5, 1->3->4,2->6]
Output:
1->1->2->3->4->4->5->6Thoughts:
With minheap:
Use minheap to add in head elements first
While heap is not empty, pull the least element o out, then if the next element of the o is not null, add it to the heap.
Iterative merging:
Code: Priority Queue T:O(NlogN) Space: O(N)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length ==0) return null;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length, (n1, n2)-> n1.val - n2.val);
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
for(ListNode node : lists){
if (node != null)
queue.add(node);
}
while(!queue.isEmpty()){
cur.next = queue.poll(); //link
cur = cur.next;
if(cur.next != null){ // put successor in the queue
queue.add(cur.next);
}
}
return dummy.next;
}
}Code: Iterative Merging T:(NlogN) Space: O(1)
Last updated
Was this helpful?