23. Merge k Sorted Lists

Problem:

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

Solutions:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    struct NodeInfo {
        ListNode* node;
        int srcList;

        NodeInfo(ListNode* node, int srcList) {
            this->node = node;
            this->srcList = srcList;
        }

        bool operator<(const NodeInfo& another) const {
            return this->node->val < another.node->val;
        }

         bool operator>(const NodeInfo& another) const {
            return this->node->val > another.node->val;
        }
    };


    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int n = lists.size();
        priority_queue<NodeInfo, vector<NodeInfo>, greater<NodeInfo>> pq;
        ListNode* dummyHead = new ListNode(0);
        ListNode* tail = dummyHead;
        for (int i = 0; i < n; ++i) {
            if (lists[i] != NULL) {
                pq.push({lists[i], i});
                lists[i] = lists[i]->next;
            }
        }

        while (!pq.empty()) {
            NodeInfo nodeInfo = pq.top(); pq.pop();
            int srcList = nodeInfo.srcList;
            ListNode* node = nodeInfo.node;
            tail->next = node;
            tail = node;
            if (lists[srcList] != NULL) {
                pq.push({lists[srcList], srcList});
                lists[srcList] = lists[srcList]->next;
            }
        }

        return dummyHead->next;
    }
};

results matching ""

    No results matching ""