A funny c++ solution, but TLE:(


  • -1
    H
     class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            return accumulate( lists.begin(), lists.end(), (ListNode*)nullptr, [&]( ListNode* head1, ListNode* head2 ) {
                ListNode* newHead = nullptr;
                ListNode* newItr = nullptr;
                
                while( head1 && head2 )
                {
                    if (head1->val < head2->val)
                    {
                        if (!newHead)
                        {
                            newItr = newHead = new ListNode( head1->val );
                        }
                        else
                        {
                            newItr = newItr->next = new ListNode( head1->val );
                        }
    
                        auto prev = head1;
                        head1 = head1->next;
                        delete prev;
                    }
                    else
                    {
                        if( !newHead )
                        {
                            newItr = newHead = new ListNode( head2->val );
                        }
                        else
                        {
                            newItr = newItr->next = new ListNode( head2->val );
                        }
    
                        head2 = head2->next;
                    }
                }
    
                while( head1 )
                {
                    if( !newHead )
                    {
                        newItr = newHead = new ListNode( head1->val );
                    }
                    else
                    {
                        newItr = newItr->next = new ListNode( head1->val );
                    }
    
                    auto prev = head1;
                    head1 = head1->next;
                    delete prev;
                }
    
                while( head2 )
                {
                    if( !newHead )
                    {
                        newItr = newHead = new ListNode( head2->val );
                    }
                    else
                    {
                        newItr = newItr->next = new ListNode( head2->val );
                    }
    
                    head2 = head2->next;
                }
    
                return newHead;
            } );
        }
    };

  • 0
    F

    Not so funny as you thought.

    Accumulating is actually a good idea, but you should not have done it sequently. Maybe divide and conquer
    would not lead to TLE.


Log in to reply
 

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