How to promote to 3ms with java?My code runs 4ms.


  • 0
    T

    /**

    • Definition for singly-linked list.
    • public class ListNode {
    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int carry = 0;
    int temp = l1.val + l2.val + carry;
    l1 = l1.next;
    l2 = l2.next;
    carry = temp / 10;
    ListNode result = new ListNode(temp-carry*10);

        ListNode tempp = result;
        while (l1 != null && l2 != null) {
            temp = l1.val + l2.val + carry;
            l1 = l1.next;
            l2 = l2.next;
            carry = temp / 10;
            result.next = new ListNode(temp-carry*10);
            result = result.next;
        }
        
        while (l1 != null) {
            temp = l1.val + carry;
            l1 = l1.next;
            carry = temp / 10;
            result.next = new ListNode(temp-carry*10);
            result = result.next;
        }
        
        while (l2 != null) {
            temp = l2.val + carry;
            l2 = l2.next;
            carry = temp / 10;
            result.next = new ListNode(temp-carry*10);
            result = result.next;
        }
        
        if (carry == 1) {
            result.next = new ListNode(1);
        }
        
        return tempp;
    }
    

    }


  • 0
    C

    hi, would you mind reformatting your code in the first several lines? :)


  • 0
    N

    From my observation, the slice difference between 3ms and 4ms due to the network condition during your submition, rather than your code speed. That time is just a reference, not accuracy time your program spend. Trust me, I have tried submit the same code for several times. Sometimes I got less time, some times I got more time.


  • 0
    J
    This post is deleted!

  • 0
    J

    You can reuse the node provided by l1, new a ListNode if carry == 1 in the last position. allocate memory is particularly time consuming.


Log in to reply
 

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