【问题标题】:using python to complete a LeetCode question #2使用 python 完成 LeetCode 问题 #2
【发布时间】:2021-10-10 06:37:42
【问题描述】:

以下是我的代码,它尝试将两个数字相加,这两个数字也以相反的顺序存储在链表中,并将总和作为链表返回。

但是当我尝试在 LeetCode 中运行这段代码时,它指出这超出了时间。我认为它可能会卡在 while 循环中?

提前感谢您的帮助。我对 Python 非常陌生,很抱歉这个愚蠢的问题。

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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode()
        carry = 0 
    
        while l1 != None or l2 != None or carry:
            if l1 == None:
                v1 = 0
            else:
                v1 = l1.val
                
            if l2 == None:
                v2 = 0
            else:
                v2 = l2.val
        
            total = v1 + v2 + carry 
            carry = total // 10
            total = total % 10
        
            result.next = ListNode(total)
            
            if l1 != None:
                l1.next
                
            if l2 != None:
                l2.next
        
        return result

【问题讨论】:

    标签: python python-3.x data-structures


    【解决方案1】:

    只有我在你写的代码中改变了一些东西。

            result = ListNode(0)
            result_tail = result #### added 
            carry = 0 
        
            while l1 or l2 or carry:
                if l1 == None:
                    v1 = 0
                else:
                    v1 = l1.val
                    
                if l2 == None:
                    v2 = 0
                else:
                    v2 = l2.val
            
                total = v1 + v2 + carry 
                carry = total // 10
                total = total % 10
            
                result_tail.next = ListNode(total)  ### edited
                result_tail = result_tail.next   ### added
                
                if l1 != None:
                    l1 = l1.next ### edited
                else:
                    l1 = None   ### added
                    
                if l2 != None:
                    l2 = l2.next    ### edited
                else:
                    l2 = None    ### added
                    
            return result.next   ### edited
    

    我希望您知道的主要事情是,当您编写 l1.next 时,您只是给出了一个命令,该命令需要一个变量来存储值,因此更改为 l1 = l1.next。 同样,当您编写相同的语句时,您需要一个 counter else 语句,当 if 条件失败时,您需要在其中处理条件。由于该条件不存在,while 循环将无限运行。

    最后一部分是我添加result_tail 的地方。通过尝试和错误,我看到如果我们不添加它,那么结果的值会被更新而不是被追加。

    最后,这不是一个愚蠢的问题。只是一个友好的建议,如果你是超级新手,不要从所有概念的简单代码开始编写中级代码。它将帮助您更多地了解 Python 中的特定交易,例如字典、默认字典、列表理解、列表遍历、元组、集合、枚举器等等。您可能较早完成了竞争性编码,但老实说,新的一局总是从 0 开始。

    如果有帮助,请点赞。

    【讨论】:

    • 您好,感谢您的帮助。但由于缺乏声誉,我无法投票。 (我刚刚在堆栈溢出中注册)。
    【解决方案2】:

    分析

    这不过是一个简单的基本加法问题。唯一的区别是要添加的数字由链表表示,其中每个数字由该链表的节点表示。

    如果我们看到这个例子,那么我们会看到数字是相反的,即,

    First node => ones place
    Second node => tens place
    Third node => hundreds place
    ... and so on.
    

    因此 2 -> 4 -> 3 实际上是 342,而 5 -> 6 -> 4 实际上是 465。

    我们将不得不返回一个新的链表,其节点将代表给定两个链表所代表的数字之和的数字。

    方法

    1. 遍历两个链表。
    2. 在每次迭代中,将链表节点中的数字相加。
    3. 如果列表不相等,则较小的列表将在较长的列表之前结束。在这种情况下,我们将只放置剩余的节点 结果列表中的列表更长。
    4. 如果两位数之和大于 9,那么我们将不得不找出要在下一次迭代中添加的“进位”。

    这只不过是一个简单的添加。这里唯一的挑战可能是避免 NullPointerException,这在基于链表的问题中很常见。

    时间复杂度

    由于我们只对两个列表进行一次迭代,因此时间复杂度为 O(m + n)。这里 m 和 n 是两个链表中的节点数。

    空间复杂度

    由于我们只为变量使用额外的空间,我们的空间复杂度将是 O(1)。有人可能会争辩说我们正在使用另一个列表来存储我们的结果,因此空间复杂度也应该是 O(m + n)。但这是我们没有用于算法的列表,我们将其用于问题中提出的结果(我很想知道您对此的看法)。

    代码

    def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
        # Head of the new linked list - this is the head of the resultant list
        head = None
        # Reference of head which is null at this point
        temp = None
        # Carry
        carry = 0
        # Loop for the two lists
        while l1 is not None or l2 is not None:
            # At the start of each iteration, we should add carry from the last iteration
            sum_value = carry
            # Since the lengths of the lists may be unequal, we are checking if the
            # current node is null for one of the lists
            if l1 is not None:
                sum_value += l1.val
                l1 = l1.next
            if l2 is not None:
                sum_value += l2.val
                l2 = l2.next
            # At this point, we will add the total sum_value % 10 to the new node
            # in the resultant list
            node = ListNode(sum_value % 10)
            # Carry to be added in the next iteration
            carry = sum_value // 10
            # If this is the first node or head
            if temp is None:
                temp = head = node
            # for any other node
            else:
                temp.next = node
                temp = temp.next
        # After the last iteration, we will check if there is carry left
        # If it's left then we will create a new node and add it
        if carry > 0:
            temp.next = ListNode(carry)
        return head
    

    希望它能解决你的问题。

    Sran012

    【讨论】:

      猜你喜欢
      • 2022-06-12
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      相关资源
      最近更新 更多