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->6
Solution:
For this problem, the brute force solution would be passing all the lists and perform Merge Sort, but for the optimal solution we will use minHeap using PriorityQueue data structure.
Note: Please try to solve it yourself before looking into the solution below
/**
* 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) {
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
for(ListNode head: lists){
while(head!=null){
minHeap.offer(head.val);
head = head.next;
}
}
ListNode returnNode = new ListNode(-1);
ListNode head = returnNode;
while(!minHeap.isEmpty()){
head.next = new ListNode(minHeap.remove());
head = head.next;
}
return returnNode.next;
}
}
Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.