C++ solution using min_heap, easy understanding


  • 4
    L
    struct compare {
        bool operator()(const ListNode *l1, const ListNode *l2) {
            return l1->val > l2->val; }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode *, vector<ListNode *>, compare> min_heap;
        ListNode *head = nullptr, **pre = &head;
        for (auto l : lists) if (l) min_heap.emplace(l);
        while (!min_heap.empty()) {
            *pre = min_heap.top();
            min_heap.pop();
            pre = &(*pre)->next;
            if (*pre) min_heap.emplace(*pre);
        }
        return head;
    }

  • 0
    L

    nice solution. beautiful code.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.