Reuse mergeTwoLists function 40ms (Merge k Sorted Lists)


  • 0
    C
        class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode * result = new ListNode(0);
            ListNode * current = result;
            while(l1&&l2)
            {
                if(l1->val <= l2->val)
                {
                    current->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    current->next= l2;
                    l2 = l2->next;
                }
                current = current->next;
            }
            current->next = l1 ? l1 : l2;
            
            return result->next;
        }
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if(lists.size()==0) return NULL;
            if(lists.size()==1) return lists[0];
            int mid = lists.size()/2;
            vector<ListNode*> left(lists.begin(),lists.begin()+mid);
            vector<ListNode*> right(lists.begin()+ mid, lists.end());
            return mergeTwoLists(mergeKLists(right),mergeKLists(left));
        }
         
    };

Log in to reply
 

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