题目
代码
执行用时:60 ms, 在所有 Python3 提交中击败了52.06% 的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了82.51% 的用户
通过测试用例:1568 / 1568
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans=now=None
pre_sum=0
while l1 and l2:
pre_sum+=l1.val+l2.val
if ans is None:
ans=now=ListNode(pre_sum%10)
else:
now.next=ListNode(pre_sum%10)
now=now.next
pre_sum//=10
l1=l1.next
l2=l2.next
ll=l1 if l1 else l2
while ll:
pre_sum+=ll.val
now.next=ListNode(pre_sum%10)
now=now.next
pre_sum//=10
ll=ll.next
while pre_sum:
now.next=ListNode(pre_sum%10)
now=now.next
pre_sum//=10
return ans

这是一个关于Python实现的链表相加算法,代码在60ms内完成,击败了52.06%的用户,同时仅使用14.9MB内存,优于82.51%的用户。该算法将两个链表的元素相加,并返回新的链表节点。
839

被折叠的 条评论
为什么被折叠?



