23. Merge k Sorted Lists

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
// Min Heap
ListNode* mergeKLists(vector<ListNode*>& lists) { // time: O(Nlogn); space: O(N), N: total listnodes, n: list number
    auto cmp = [] (ListNode*& a, ListNode*& b) {
        return a->val > b->val;
    };
    // minHeap for ListNode
    priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);
    for (ListNode*& list : lists) {
        if (list) pq.push(list);
    }
    ListNode *head = nullptr, *pre = nullptr, *tmp = nullptr;
    while (!pq.empty()) {
        tmp = pq.top(); pq.pop();
        if (!pre) head = tmp;
        else pre->next = tmp;
        pre = tmp;
        if (tmp->next) pq.push(tmp->next);
    }
    return head;
}
// struct cmp {
//     bool operator() (ListNode*& a, ListNode*& b) {
//         return a->val > b->val;
//     };
// };

Last updated

Was this helpful?