Why my solution got Time Limit Exceeded?


  • 0
    S
    class Solution {
    public:
        ListNode *sortList(ListNode *head) {
            if(head==NULL||head->next==NULL)
                return head;
            ListNode *fast = (head->next)->next;
            ListNode *slow = head;
            while(fast!=NULL&&(fast->next)!=NULL){
                fast = (fast->next)->next;
                slow = slow->next;
            }
            ListNode *list2 = sortList(slow->next);
            slow->next=NULL;
            ListNode *list1 = sortList(head);
            return merge(list1,list2);
        }
        ListNode *merge(ListNode *head1, ListNode *head2){
            ListNode *magic =new ListNode(0);
            ListNode *p = magic;
            while(head1!=NULL&&head2!=NULL){
                if((head1->val)>(head2->val)){
                    p->next = head2;
                    head2 = head2->next;
                }
                else{
                    p->next = head1;
                    head1 = head1->next;
                }
                p = p->next;
            }
            while(head1!=NULL){
                p->next = head1;
            }
            while(head2!=NULL){
                p->next = head2;
            }
            return magic->next;
        }
    };

  • 0
    S

    Questions about code you've written must describe the specific problem clearly, elaborate thoughts based on code and preserve code formatting as well. Please read the FAQ for more info.


  • 0
    S

    you can try replace while(head1!=NULL) with if(head1!=NULL)


  • 0
    X

    yeah,you are right


Log in to reply
 

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