[Leetcode C++] Merge k Sorted Lists

Problem

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Analysis

We can recursively merge two lists into one list

Let k denote the number of lists
Let n denote the average length of each list
Time complexity: T(k) = 2T(k/2) + O(nk), thus we have O(nk*log k)
Space complexity:

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.size() == 0) return NULL;
        if(lists.size() == 1) return lists[0];
        
        //merge each two lists into one
        vector<ListNode*> newLists;
        int n = lists.size();
        for(int i=0; i<n/2; i++){
            ListNode* currList = helper(lists[i], lists[n-1-i]);
            newLists.push_back(currList);
        }
        if(n%2 != 0){
            newLists.push_back(lists[n/2]);
        }
        
        //recursively merge all the lists
        return mergeKLists(newLists);
    }
    
    //merge two lists
    ListNode* helper(ListNode* l1, ListNode* l2){
        ListNode* dummyHead = new ListNode(-1);
        ListNode* l = dummyHead;
        while(l1 && l2){
            if(l1->val <= l2->val){
                l->next = l1;
                l1 = l1->next;
            }else{
                l->next = l2;
                l2 = l2->next;
            }
            l = l->next;
        }
        l->next = l1? l1 : l2;
        return dummyHead->next;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *

*