TLE problem.Help me Please


  • 0
    M

    ListNode *detectCycle(ListNode *head) {

        if(!head)
        return nullptr;
        
        ListNode* quick=head->next,*slow=head;
        
        while(quick)
        {
            if(quick==slow)
            break;
            quick=quick->next;
            if(quick)
            quick=quick->next;
            slow=slow->next;
        }
        if(!quick)
        return nullptr;
        
        slow=head;
        while(quick!=slow)
        {
            
            slow=slow->next;
            quick=quick->next;
        
        }
      
        return quick;
    }
    

    Where it goes wrong? Please


  • 0
    L

    Add "else" around slow=head;
    while(quick!=slow)
    {

        slow=slow->next;
        quick=quick->next;
    
    }
    
    return quick;
    

    then it will be accepted .


Log in to reply
 

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