Two Approach:
/*Solution1:
* KeyWord: MergeSort,Iteration
* Approach:
* 1. Divide K linked list into k/2 linked list
* 2. Merge two separated each time iteratively.
* example of k=6;
* => merge 1 and 4; save on 1
* => merge 2 and 5; save on 2
* => merge 3 and 6; save on 3
* then merge 1 and 2 (as a result: merge of 14 and 25); save on 1
* => merge 1 and 3 (as a result: merge of 1425 and 36); save on 1
* return 1;
* Time analysis:
* T(k)= 2T(k/2) + O(n*k)
* in total:=> O(k*n*logk)
* Space Complexity: O(logk) not including space cost during recursive
*/
public ListNode mergeKListsMerge(List<ListNode> lists) {
int k=lists.size();
if(k==0) return null;
else{
while(k >1)
{
int mid= (k+1)/2;
for(int i = 0; i < k/2; i++){
lists.set(i, mergeTwoLists(lists.get(i), lists.get(i + mid)));
}
k = mid;
}
return lists.get(0);
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//check for base case
if(l1==null) return l2;
if(l2==null) return l1;
if(l1==null && l2==null) return l1;
//delcare a dummy node
ListNode dummy=new ListNode(0);
//delcare a temple ListNode ll
ListNode ll=dummy;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
ll.next=l1;
l1=l1.next;
}else{
ll.next=l2;
l2=l2.next;
}
ll=ll.next;
}
if(l1!=null){
ll.next=l1;
}else{
ll.next=l2;
}
return dummy.next;
}
/*Solution2:
* KeyWord: PriorityQueue
* Approach:
* it require to sort input lists, and merge together, then output one.
* 1. Use the DataStructure of PriorityQueue that
* 2. The idea in behind is to always keep smallest element in the top of heap.
* Time analysis: since it require go over each element once => O(k*n),
* insert operation in PriorityQueue => O(logk)
* k is size of PriorityQueue Time complexity in total:=> O(k*n*logk)
* Space Complexity: O(k) size of PriorityQueue
*/
public ListNode mergeKLists(List<ListNode> lists) {
if(lists.size()==0) return null;
// define a ListNode Comparator
Comparator<ListNode> compListNode = new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
if (a.val > b.val)
return 1;
else if (a.val < b.val)
return -1;
else
return 0;
// Assume neither ListNode is null.
// You could also just return x.val - y.val
// which would be more efficient.
}
};
// define a PriorityQueue object
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.size(),
compListNode);
// travel each ListNode from lists
Iterator itr = lists.iterator();
while (itr.hasNext()) {
ListNode l = (ListNode) itr.next();
if (l != null) {
pq.add(l);
}
// System.out.println(l.printForward());
}
//merge into a single linkedlist
ListNode merge = new ListNode(0);
ListNode cur=merge;
while(pq.size()>0){
ListNode temp=pq.poll();
//connect cur->temp;
cur.next=temp;
if(temp.next!=null){
pq.add(temp.next);
}
cur=cur.next;
}
return merge.next;
}