23. Merge k Sorted Lists

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

合并k个有序列表。

(1)堆排序

bool cmp(ListNode *l1,ListNode *l2){
    return l1->val > l2->val;
 }
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        vector<ListNode*> validLists;
        for(auto i:lists)
            if(i) validLists.push_back(i);
        ListNode *pre = new ListNode(-1);
        ListNode *curr = pre;
        make_heap(validLists.begin(),validLists.end(),cmp);
        while(!validLists.empty()){
            ListNode *top = validLists.front();
            pop_heap(validLists.begin(),validLists.end(),cmp);
            validLists.pop_back();
            curr->next = top;
            curr = curr->next;
            top = top->next;
            if(top){
                validLists.push_back(top);
                push_heap(validLists.begin(),validLists.end(),cmp);
            }
        }
        return pre->next;
    }
};

(2)两两合并

//merge two lists recursive version

//time complexity: O(klogk)
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0) return NULL;
        int n = lists.size();
        return merge(lists, 0, n - 1);
    }

    ListNode * merge(vector<ListNode *>& lists, int begin, int end) {
        if (begin > end) return NULL;
        if (begin == end) return lists[begin];
        if (begin + 1 == end) return mergeTwoList(lists[begin], lists[end]);
        int mid = begin + (end - begin) / 2;
        ListNode * firstHalf = merge(lists, begin, mid);
        ListNode * secondHalf = merge(lists, mid + 1, end);
        return mergeTwoList(firstHalf, secondHalf);
    }

    ListNode* mergeTwoList(ListNode* l1, ListNode* l2) {
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        if (l1->val < l2->val) {
            ListNode * head = l1;
            head->next = mergeTwoList(l1->next, l2);
            return head;
        } else {
            ListNode * head = l2;
            head->next = mergeTwoList(l1, l2->next);
            return head;
        }
    }
};

 

以上是关于23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists