C++ solution using priority queue with Lambda


  • 0
    N
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            auto cmp = [](const ListNode* lhs, const ListNode* rhs) { return lhs->val > rhs->val; };
            priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> min_heap(cmp);
            for (const auto& list : lists) {
                if (list) min_heap.push(list);
            }
            ListNode dummy_head(INT_MIN), *curr = &dummy_head;
            while (!min_heap.empty()) {
                ListNode* node = min_heap.top();
                min_heap.pop();
                curr->next = node;
                curr = curr->next;
                if (node->next) {
                    min_heap.push(node->next);
                }
            }
            
            return dummy_head.next;
        }
    };
    

Log in to reply
 

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