C++ priority queue simple


  • 0
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            auto cmp = [](ListNode* a, ListNode* b) {
                return a->val > b->val;
            };
            priority_queue<ListNode*,vector<ListNode*>,decltype(cmp)> pq(cmp);
            ListNode *head = new ListNode(0);
            ListNode *tmp = head;
            for(auto node : lists) {
                if(!node) continue;
                pq.push(node);
            }
            while(!pq.empty()) {
                head->next = pq.top();
                pq.pop();
                head = head->next;
                if(head->next) {
                    pq.push(head->next);
                }
            }
            return tmp->next;
        }
    };
    

Log in to reply
 

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