[CPP]Time Limited Exceeded? Why?


  • 0

    I think my program can be accepted but it doesn't. I cannot find where I am wrong. I need a help.
    As is followed, this is my code.

    class Solution
    {
    	public:
    	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    	{
    		int temp = 0;
    		ListNode* l3 = NULL;
    		ListNode* p = l3;
    
    		while(l1&&l2)
    		{
    			int sum = l1->val + l2->val + temp;
    			temp = sum / 10;
    			
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    
    			p->next = l3_ptr;
    			p = p->next;
    			l1 = l1->next;
    			l2 = l2->next;
    		}
    		while(l1)
    		{
    			int sum = l1->val + temp;
    			temp = sum / 10;
    
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    			p->next = l3_ptr;
    			p = p->next;
    			l1 = l1->next;
    		}
    		while(l2)
    		{
    			int sum = l2->val + temp;
    			temp = sum / 10;
    
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    
    			p->next = l3_ptr;
    			p = p->next;
    			l2 = l2->next;
    		}
    		if(temp)
    		{
    			ListNode* l3_ptr = new ListNode(temp);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    
    			p->next = l3_ptr;
    		}
    		return l3;
    	}
    	
    };
    

  • 0

    I dont use a dummy head in the above code.But i dont think it is the reason my time exceeded.
    And this is an accepted code. I think the code is the same as mine.

    class Solution
    {
    public:
    	ListNode *addTwoNumbers( ListNode *l1, ListNode *l2 )
    	{
    		ListNode* l3 = new ListNode( 0 );
    		ListNode* p = l3;
    		int carry = 0;
    		while ( l1&&l2 )
    		{
    			int sum = l1->val + l2->val + carry;
    			ListNode* tem = new ListNode( sum % 10 );
    			p->next = tem;
    			p = p->next;
    			carry = sum / 10;
    			l1 = l1->next;
    			l2 = l2->next;
    		}
    		while ( l1 )
    		{
    			int sum = l1->val + carry;
    			ListNode* tem = new ListNode( sum % 10 );
    			p->next = tem;
    			p = p->next;
    			carry = sum / 10;
    			l1 = l1->next;
    		}
    		while ( l2 )
    		{
    			int sum = l2->val + carry;
    			ListNode* tem = new ListNode( sum % 10 );
    			p->next = tem;
    			p = p->next;
    			carry = sum / 10;
    			l2 = l2->next;
    		}
    		if ( carry )
    		{
    			ListNode* tem = new ListNode( carry );
    			p->next = tem;
    			p = p->next;
    		}
    		return l3->next;
    	}
    };
    

Log in to reply
 

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