LeetCode刷题记(二)--Python

835 阅读2分钟

[LeetCode] Add Two Numbers 两个数字相加

难度: 中等 刷题内容 原题连接leetcode-twosum

内容描述

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

简单翻译一下

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

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

题意理解

这道并不是什么难题,算法很简单,链表的数据类型也不难,就是建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面。

解题思路及方案

定义节点,使用:类+构造方法,构造方法的参数要有节点的数值大小、对下一个节点的指针等。 若 l1 表示一个链表,则实质上 l1 表示头节点的指针。 先实例一个头结点,然后在 while 循环中逐个加入节点。 del ret 删除头结点。

关键解析

head是一个哑节点(dummy node),可以简化代码。 python的对象分为两种:可变对象与不可变对象。 整数属于不可变对象,当改变j的值时,相当于新建了一个整数对象重新赋值给j,故不会改变i的值。而l和head指向的是可变对象,因而l变化了,head也会随之变化。

Python解法

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

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        if l1 == None: return l2
        if l2 == None: return l1
        flag = 0
        dummy = ListNode(0); p = dummy
        while l1 and l2:
            p.next = ListNode((l1.val+l2.val+flag) % 10)
            flag = (l1.val+l2.val+flag) / 10
            l1 = l1.next; l2 = l2.next; p = p.next
        if l2:
            while l2:
                p.next = ListNode((l2.val+flag) % 10)
                flag = (l2.val+flag) / 10
                l2 = l2.next; p = p.next
        if l1:
            while l1:
                p.next = ListNode((l1.val+flag) % 10)
                flag = (l1.val+flag) / 10
                l1 = l1.next; p = p.next
        if flag == 1: p.next = ListNode(1)
        return dummy.next
  • 提交执行用时战胜85.99%挑战提交记录
  • 执行用时68ms

Python3

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

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        head = ListNode(0)
            l.next = ListNode(sum)
            l = l.next
        return head.next


  • 提交执行用时战胜99.40%挑战提交记录
  • 执行用时88ms