我真是个大菜B*10
幸好leetcode的内存给的比较宽松 不然妥妥的内存超限。
Submission Detail
1563 / 1563 test cases passed.
|
Status:
Accepted |
Runtime: 88 ms
Memory Usage: 13.3 MB
|
Submitted: 4 minutes ago
|
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: arr1 = [] arr2 = [] # l1------------ while (l1.next != None): arr1.append(l1.val) l1 = l1.next arr1.append(l1.val) # l2------------ while (l2.next != None): arr2.append(l2.val) l2 = l2.next arr2.append(l2.val) #add 0 to fit length if len(arr1) >= len(arr2): temp = len(arr1) - len(arr2) for index in range(temp): arr2.append(0) else: temp = len(arr2) - len(arr1) for index in range(temp): arr1.append(0) # reverse------------ rev_arr1 = arr1[::-1] rev_arr2 = arr2[::-1] # calculate------------ i = len(rev_arr1) - 1 sum = [0 for i in range(i + 1 )] #init sum and filled with 0 carry = 0 while (i >= 0): if carry == 1: rev_arr1[i] +=1 carry = 0 if (rev_arr1[i] + rev_arr2[i]) > 9: sum[i] = rev_arr1[i] + rev_arr2[i] - 10 carry = 1 else: sum[i] = rev_arr1[i] + rev_arr2[i] i = i - 1 # output------------ #print(sum[::-1]) sum =sum[::-1] #deal with carry number such as 5+5 = 10 if carry == 1: sum.append(1) FirstNode = ListNode(sum[0]) indexNode = FirstNode for i in range(1,len(sum)): tempNode = ListNode(sum[i]) indexNode.next = tempNode indexNode = tempNode return FirstNode