2. 两数相加
题意
倒序的数字进行相加;
解题思路
数字进行倒序还算是简单的,因为我们正常的运算也是从按照这个顺序,正好可以方便计算;
实现中的两个方法是一样的,不太懂为啥下面的运行时间查这么多;
实现
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
执行用时 : 128 ms, 在Add Two Numbers的Python提交中击败了7.75% 的用户
内存消耗 : 11 MB, 在Add Two Numbers的Python提交中击败了0.86% 的用户
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
is_decimal = False
while l1 and l2:
is_decimal, value = self.get_add_result(val1=l1.val, val2=l2.val, is_decimal=is_decimal)
node = ListNode(value)
cur.next = node
cur = cur.next
l1 = l1.next
l2 = l2.next
while l1:
is_decimal, value = self.get_add_result(val1=l1.val, is_decimal=is_decimal)
node = ListNode(value)
cur.next = node
cur = cur.next
l1 = l1.next
while l2:
is_decimal, value = self.get_add_result(val2=l2.val, is_decimal=is_decimal)
node = ListNode(value)
cur.next = node
cur = cur.next
l2 = l2.next
if is_decimal:
node = ListNode(1)
cur.next = node
return dummy.next
def get_add_result(self, val1=0, val2=0, is_decimal=False):
value = val1 + val2 + int(is_decimal)
if value >= 10:
value %= 10
is_decimal = True
else:
is_decimal = False
return is_decimal, value
def addTwoNumbers2(self, l1, l2):
"""
执行用时 : 84 ms, 在Add Two Numbers的Python提交中击败了85.84% 的用户
内存消耗 : 11 MB, 在Add Two Numbers的Python提交中击败了0.86% 的用户
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
digit = 0
while l1 or l2 or digit:
if l1:
digit += l1.val
l1 = l1.next
if l2:
digit += l2.val
l2 = l2.next
node = ListNode(digit % 10)
cur.next = node
cur = cur.next
digit //= 10
return dummy.next
提升
如果这个链表存储的数字的顺序是正常的话,那么有两种方法:
将链表进行倒序,接着就和上面的实现一样了;
利用栈将两个链表的值倒序取出来,思想和上面的思想一样;