Python beats 99%, using O(1) space


  • 0
    Z

    Idea is use list1 as your output list, change node on list1 directly

    def addTwoNumbers(self, l1, l2):
            dummy = ListNode(0)
            dummy.next = l1
            carry = 0
            prev = dummy
            while not(l1 is None and l2 is None):
                if l1 is None: #in case l1 is the shorter one
                    prev.next = l2
                    tmp = l2
                    l2 = l1
                    l1 = tmp
                v1 = l1.val
                v2 = 0
                if l2 is not None:
                    v2 = l2.val
                s = v1 +v2 +carry
                digit = s%10
                carry = s/10
                l1.val = digit
                prev = prev.next
                l1 = l1.next
                if l2 is not None:
                    l2 = l2.next
            if carry!=0:
                prev.next =ListNode(carry)
            return dummy.next
    

Log in to reply
 

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