You are given an array of linked lists, each of which has been sorted in ascending order. Please merge all lists into one ascending list and return the merged list.

Example 1:

Input: lists = [].enlighened by [1 4], [2, 6]] output:,1,2,3,4,4,5,6 [1] : list array is as follows: [1 - > > 5, 4-1 - > 3 - > 4, 6] 2 - > merge them into an ordered list. 1 - > 1 - > 2 - > 3 - > 4 - > 4 - > 5 - > 6Copy the code

Example 2:

Input: Lists = [] Output: []Copy the code

Example 3:

Input: Lists = [[]] Output: []Copy the code

This problem is similar to LeetCode 21 last time. Actually, problem 21 is a subproblem of this problem.

After solving problem 21, we can know how to combine two ascending linked lists. So, the question becomes, how do we merge k ascending lists the fastest? In what order?

Here we use merge: merge sort

You can then use the mergeTwoLists function encapsulated in the previous problem, and write a mergeNode function based on merge sort to determine the two lists to merge each time

var mergeKLists = function(lists) {
    if(!lists.length)return null;
    if(lists.length===1)return lists[0];
    
    return mergeNode(lists,0,lists.length-1);
};
var mergeNode = function(lists,start,end) {
    if(start==end){return lists[start];}
    var mid = Math.floor((end+start)/2);
    var l1 = mergeNode(lists,start,mid);
    var l2 = mergeNode(lists,mid+1,end);
    return mergeTwoLists(l1,l2);
};
function mergeTwoLists(l1,l2){
    if(l1===null){
        return l2;
    }else if(l2===null){
        return l1;
    }
    while(l1){
        if(l1.val<=l2.val){
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}
Copy the code

This is the first hard problem I have done. When I first wrote it, I was actually quite afraid, but when I thought about it, most difficult problems can be broken down into several small sub-problems to solve, so I just need to be patient.