Help "Memory Limit Exceeded"


  • 1
    W

    My code

        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ListNode* l3;ListNode* l;int temp=0;int mark=0;//mark means a carry digit
        l=l3;// l=head
        while(l1||l2){
            if(l1&&l2){temp=l1->val+l2->val+mark;mark=0;}// sum two digit and carry digit,then reset the carry digit
            if(l1&&!l2){temp=l1->val+mark;mark=0;}
            if(!l1&&l2){temp=l2->val+mark;mark=0;}
            if(temp>9){temp=temp-10;mark=1;}// when the sum bigger than 9,set the carry digit to 1
            ListNode *t=new ListNode(temp);
            l3->next=t;
            l3=t;
        }
        if(mark){ListNode * tt=new ListNode(mark);l3->next=tt;}
        return l->next;
    }
    

    I don't know why it reports Memory Limit Exceeded


  • 0
    S

    Could you please add some words about your thought, and make some comments in your code?


  • 0
    W

    I have added some comments, is that ok?


  • 0
    S

    Yes, it looks good now.


  • 5
    S

    Seems the problem is that you do not move your l1 and l2, so the while loop will not exit. Then the ListNode *t=new ListNode(temp); will always allocate new memory space, which hits the memory limit.


Log in to reply
 

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