Why my 4ms cpp recursion solution slows down after the following modification?


  • 0
    D

    Here is my 4ms solution.

     ListNode* removeNthFromEnd(ListNode* head, int n) {
            Delete(head, n);
            return head;
     }
    
    int Delete(ListNode*& head, int n){
        int count = 0;
        if(head != NULL)
            count = Delete(head->next, n) + 1;
        if(count == n){
            ListNode* temp = head;
            head = head->next;
            delete temp;
        }
        return count;
    }
    

    However, if I change all 'head' to 'temp' in function Delete() like this, it slows down to 12ms. Not exactly sure about why?

    int Delete(ListNode*& temp, int n){
        int count = 0;
        if(temp != NULL)
            count = Delete(temp->next, n) + 1;
        if(count == n){
            ListNode* target = temp;
            temp = temp->next;
            delete target;
        }
        return count;
    }

Log in to reply
 

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