[LeetCode] Merge k Sorted Lists

 

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

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
bool cmp(const ListNode* a, const ListNode* b) {
    return a->val > b->val;
}
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode* head, *cur;
        auto it = remove_if(lists.begin(), lists.end(), [](const ListNode* a) {return a == NULL;});
        lists.erase(it, lists.end());
        make_heap(lists.begin(), lists.end(), cmp);
        if (lists.size() == 0) return NULL;
        pop_heap(lists.begin(), lists.end(), cmp);
        auto end = lists.end() - 1;
        head = *end;
        *end = head->next;
        if (*end == NULL) {
            lists.erase(lists.end()-1);
        } else {
            push_heap(lists.begin(), lists.end(), cmp);
        }
        cur = head;
        while (!lists.empty()) {
            pop_heap(lists.begin(), lists.end(), cmp);
            auto end2 = lists.end() - 1;
            cur->next = *end2;
            cur = cur->next;
            *end2 = cur->next;
            if (*end2 == NULL) {
                lists.erase(lists.end()-1);
            } else {
                push_heap(lists.begin(), lists.end(), cmp);
            }
        }
        return head;
    }
};

 

你可能感兴趣的:(LeetCode)