My C++ 388ms solution


  • 0
    M
    struct OrderByFirstNode {
        inline bool operator () (ListNode* a, ListNode* b) {
            return a->val > b->val;
        }
    };
    typedef priority_queue<ListNode*, vector<ListNode *>, OrderByFirstNode> node_queue_t;
     
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            node_queue_t node_queue;
            ListNode dummy(0);
            ListNode *tail = &dummy;
            for (ListNode* node : lists) {
                if (node) {
                    node_queue.push(node);
                }
            }
            
            while (!node_queue.empty()) {
                ListNode *node = node_queue.top();
                node_queue.pop();
                tail->next = node;
                tail = tail->next;
                if (node->next) {
                    node_queue.push(node->next);
                }
            }
            
            return dummy.next;
        }
    };

Log in to reply
 

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