【问题标题】:How to delete consecutive elements in a linked list which add up to 0如何删除链表中加起来为0的连续元素
【发布时间】:2019-12-28 10:41:22
【问题描述】:

我正在编写一个 Python 代码来删除链表中的那些连续元素,它们加起来为 0

链表定义如下:

class Node:
    def __init__(self, val, next=None):
        self.value = val
        self.next = next

node = Node(10)
node.next = Node(5)
node.next.next = Node(-3)
node.next.next.next = Node(-3)
node.next.next.next.next = Node(1)
node.next.next.next.next.next = Node(4)
node.next.next.next.next.next.next = Node(-4)

根据上述数据,5 -> -3 -> -3 -> 14 -> -4 需要被排除,因为它们加起来是 0

遍历元素后,如

def removeConsecutiveSumTo0(node):
    start = node
    while start:
        mod = False
        total = 0
        end = start

        while end:
            total += end.value
            if total == 0:
                start = end
                mod = True
                break
            end = end.next

        if mod == False:
            res = start

        start = start.next

    return res

node = removeConsecutiveSumTo0(node)
while node:
    print (node.value, end=' ')
    node = node.next
# 10 (Expected output)

我无法创建包含加起来为0 的连续元素的子集。因为它是NP-Complete problem 讨论的herehere。如何设计算法来找到解决方案?

【问题讨论】:

  • 作为提示,您可以使用“真实示例”。所以不要担心问题本身是不是一般的 np-hard 问题,你总是可以在遍历节点时蛮力计算你的方式。跟踪每个节点的所有个可能的总和,如果在迭代过程中总和达到0,则消除整个链。
  • 回复:“我无法创建包含加起来为 0 的连续元素的子集。因为它是 NP-Complete problem”:这是不正确的。寻找总和为零的任意子集是NP完全的;但是找到总和为零的 连续子列表 可以在 O(n^2) 时间内完成。 (另外,我的意思是,即使是 NP 完全问题也可以解决;只是如果输入太大,那么它会花费太长时间。)

标签: python algorithm linked-list subset-sum np-complete


【解决方案1】:

您可以尝试递归或嵌套循环,因为您应该在计算总和时尝试从每个节点开始。一个简单的实现可能如下:

def removeConsecutiveSumTo0(node):
  start = node
  while start.next:
    total = 0
    cur = start.next
    while cur:
      total += cur.value
      if total == 0:
        start.next = cur.next
        break
      cur = cur.next
    else:
      start = start.next

【讨论】:

  • 我稍微修改了一下,得到了解决方案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
相关资源
最近更新 更多