Add two numbers, java 388ms. How to optimize or decrease run time?


  • 0
    M

    Any suggestions on how to optimize or decrease run time?
    Any other suggestions, comments, criticism is welcome.

      public class Solution {
            ListNode l3;
            ListNode h3;
            boolean  remainder;
            public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
            	if(l1 == null && l2 == null)
            		return null;
            		
            	while(l1 != null || l2 != null || remainder){
            		addNode(l1, l2);
           		if(l1 != null)
            		l1 = l1.next;
            	if(l2 != null)
            		l2 = l2.next;
            	}
            	return h3;
            }
            
            protected void addNode(ListNode l1, ListNode l2){
            	byte addResult = (byte) ((l1 != null)? l1.val : 0);
            	addResult += (byte) ((l2 != null)? l2.val : 0);
            	if(remainder)
            		++addResult;
            	
            	remainder = addResult > 9;
            	
            	if(remainder)
            		addNewNodeToList(addResult % 10);
            	else
            		addNewNodeToList(addResult);
            }
        
            protected void addNewNodeToList(int addResult){
        	    if(l3 == null){
        		    l3 = new ListNode(addResult);
        		    h3 = l3;
        	    }
                else{
        		    l3.next = new ListNode(addResult);
        		    l3 = l3.next;
        		}
            }
        }

  • 0
    A

    our solutions are similar but I guess the function addNewNodeToList(int addResult) is not necessary.
    this function here will check if(l3 == null) every time.
    instead, you can initialize h3 = new ListNode(0) and set l3 = h3 before the while loop.
    and each time you got a new node you can just append it to l3 and update l3=l3.next
    After you finish everything, you can just return h3.next

    the code will looks like:

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
            if(l1 == null)
                return l2;
            if(l2 == null)
                return l1;  //I also changed the code here a little
    
            ListNode h3 = new ListNode(0);
            ListNode l3 = h3;
    
            while(l1 != null || l2 != null || remainder){
                //your code here
    
                l3.next = new ListNode(addResult);
                l3 = l3.next;
            }
            return h3.next;
        }

  • 0
    M

    Thanks, that's smart. I thought of something similar but lost it in my "initial over analysis" of the problem.


Log in to reply
 

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