C++ 48ms using priority_queue


  • 0
    X
    class Solution {
    public:
        struct mycmp{
          bool operator()(const ListNode* lhs, const ListNode* rhs){
              return lhs->val > rhs->val;
          }  
        };
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            int size = lists.size();
            if(size == 0){
                return NULL;
            }
            priority_queue<ListNode*, vector<ListNode*>, mycmp> q;
            for(int i = 0; i < size; ++i){
                if(lists[i] != NULL){
                    q.push(lists[i]);
                }
            }
            ListNode* head = new ListNode(-1);
            ListNode* p = head;
            while(!q.empty()){
                ListNode* t = q.top();
                q.pop();
                if(t->next != NULL){
                    q.push(t->next);
                }
                p->next = t;
                p = t;
            }
            ListNode* ans = head->next;
            delete head;
            return ans;
        }
    };

Log in to reply
 

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