C++ 10 lines min heap


  • 2
    V
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode* root = nullptr, *p = nullptr;
        priority_queue <pair<int, ListNode*>, vector<pair<int, ListNode*>>, greater<pair<int, ListNode*>> > q;
        for (auto i = 0; i < lists.size(); ++i) 
            if (lists[i] != nullptr) q.push({lists[i]->val, lists[i]});
        while (!q.empty()) {
            if (root == nullptr) root = p = q.top().second;
            else p = p->next = q.top().second;
            q.pop();
            if (p->next != nullptr) q.push( {p->next->val, p->next });
        }
        return root;
    }
    

Log in to reply
 

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