天天看点

【LeetCode 中等题】1-两数之和声明:正文结尾

声明:

今天是中等题第1道题。求2个链表之和。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807      

解法1。常规解法,新开辟一条链表存储两个链表之和,并用carry记录当前进位情况,代码如下。

执行用时: 200 ms, 在Add Two Numbers的Python3提交中击败了20.01% 的用户

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        if not l2:
            return l1
        
        carry = 0
        dummy = ListNode(0)
        head = dummy
        while not l1 or not l2:
            sum_m = 0
            if l1:
                sum_m = l1.val
                l1 = l1.next
            if l2:
                sum_m += l2.val
                l2 = l2.next
            sum_m += carry
            carry = sum_m//10
            dummy.next = ListNode(sum_m%10)
            dummy = dummy.next
        if carry == 1:
            dummy.next = ListNode(1)
        return head.next
            
        
           

解法2。可以选择就地修改l1,当其中1条更短的链表遍历完了就遍历剩下的部分,代码如下。

执行用时: 152 ms, 在Add Two Numbers的Python3提交中击败了79.06% 的用户 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        sum_m = 0
        carry = 0
        head = ListNode(0)
        head.next = l1
        while l1 and l2:
            sum_m = l1.val + l2.val + carry
            carry = sum_m//10
            l1.val = sum_m%10
            prev = l1
            l1 = l1.next
            l2 = l2.next
        l = l1 or l2    # 取较长链表没被遍历过的那一部分
        prev.next = l
        while l and carry:
            sum_m = l.val+carry
            l.val = sum_m%10
            carry = sum_m//10
            prev = l
            l = l.next
        if carry == 1:
            prev.next = ListNode(1)
        return head.next
           

结尾

解法1:官方解法

解法2:LeetCode