TLE on last test case?


  • 0
    S
    class Solution {
        
        ListNode* splitLists(ListNode* head)
        {
            ListNode* slow = head;
            ListNode* fast = head;
            while(fast->next && fast->next->next)
            {
                slow = slow->next;
                fast = fast->next;
            }
            
            //slow points to end of first list
            ListNode* head2 = slow->next;
            slow->next = nullptr;
            return head2;
        }
        
        ListNode* merge(ListNode* head1, ListNode* head2)
        {
            ListNode* newHead = new ListNode(0);
            ListNode* curr = newHead;
            
            while(head1 && head2)
            {
                if (head1->val < head2->val)
                {
                    curr->next = head1;
                    head1 = head1->next;
                }
                else
                {
                    curr->next = head2;
                    head2 = head2->next;
                }
                curr = curr->next;
            }
            
            if (head1)
                curr->next = head1;
                
            if (head2)
                curr->next = head2;
            
            return newHead->next;
        }
    public:
        ListNode* sortList(ListNode* head) {
            if (!head || !head->next)
                return head;
            
            ListNode* head2 = splitLists(head);
            ListNode* list1 = sortList(head);
            ListNode* list2 = sortList(head2);
            
            return merge(list1, list2);
        }
    };
    

    Why does this TLE on the last test case?


Log in to reply
 

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