Concise C++ Solution


  • 0
    I
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            ListNode h = ListNode(0);
            ListNode *p = &h;
            int n = lists.size();
            if (n==0) return NULL;
            make_heap(lists.begin(), lists.end(), compare);
            while (lists[0] != NULL) {
                p->next = lists[0];
                p = p->next;
                pop_heap(lists.begin(), lists.end(), compare);
                lists[n-1] = lists[n-1]->next;
                push_heap(lists.begin(), lists.end(), compare);
            }
            return h.next;
        }
    private:
        static bool compare(ListNode *a, ListNode *b) {
            if (a == NULL) return true;
            if (b == NULL) return false;
            if (a->val > b->val) return true;
            else                 return false;
        }
    };
    

Log in to reply
 

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