"""
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted. Example 2: Input: head = [1,2,3,-3,4]
Output: [1,2,4] Example 3: Input: head = [1,2,3,-3,-2]
Output: [1] """
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None class Solution1(object):
def removeZeroSumSublists(self, head):
"""
:param head: ListNode
:return: ListNode
"""
if not head.next:
return head if head.val != 0 else None #判断头节点是为否为空
list = [] #建立list存储链表转化后的数组
p = head #建立p指针指向头结点
while(p): #将链表转为数组
list.append(p.val)
p = p.next
list = self.remove(list) #!!!删除连续和为0
newhead = ListNode(-1) #建立新的头结点
p = newhead #p指向新的头结点
for num in list: #将结果数组转成链表
p.next = ListNode(num)
p = p.next
return newhead.next
"""
在一个数组里把连续和为0的部分删除,两层循环:用i对每个元素遍历
再用j不断的对当前子数组求和,若为0,删除当前部分并进行递归
"""
def remove(self, list): #在一个数组里把连续和为0的部分删除
for i in range(len(list)):
sum = list[i]
j = i + 1
while(j <= len(list)):
if sum == 0:
return self.remove(list[:i] + list[j:]) #递归处理
else:
if j == len(list):
break
sum += list[j]
j += 1
return list """
用一个变量pre_sum记录前缀和,再用一个哈希表记录出现过的前缀和,
如果出现了两个相同的前缀和,就说明中间这一段的和为0,是多余的。
举例:
对于输入 [1, 2, -2, 3, -1, -1, -1],
前缀和为[1, 3, 1, 4, 3, 2, 1],
下标为0的1和下标为2的1相同,
就代表下标在【1, 2】间的元素的和为0。
"""
class Solution2(object):
def removeZeroSumSublists(self, head):
"""
:param head: ListNode
:return: ListNode
"""
dummy = ListNode(-1) #用一个假头结点dummy返回结果,
dummy.next = head #防止头节点head被删除无法返回
pre_sum = 0 #记录前缀和
record = {0: dummy} # 用dict来存出现过的每个前缀和
# bug代码record = {0,dummy} 这里需要对record初始化{:}
while head:
pre_sum += head.val # bug代码 马虎没有写'+'
if pre_sum in record:
record[pre_sum].next = head.next #寻找是否有重复的元素
else: #类似于leetcode1:twoSum
record[pre_sum] = head
head = head.next
return dummy.next #用dummy来返回结果
"""
Wrong answer
Input
[1,3,2,-3,-2,5,5,-5,1]
Output
[1,5,5,-5,1]
Expected
[1,5,1]
"""

leeetcode1171 Remove Zero Sum Consecutive Nodes from Linked List的更多相关文章

  1. 【leetcode】1171. Remove Zero Sum Consecutive Nodes from Linked List

    题目如下: Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum ...

  2. 【LeetCode】1171. Remove Zero Sum Consecutive Nodes from Linked List 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 preSum + 字典 日期 题目地址:https:/ ...

  3. [LintCode] Swap Two Nodes in Linked List 交换链表中的两个结点

    Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 a ...

  4. Swap Two Nodes in Linked List

    Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 a ...

  5. LintCode "Swap Two Nodes in Linked List"

    Nothing special. Just take care of corner cases. class Solution { public: /** * @param head a ListNo ...

  6. [LeetCode] 83. Remove Duplicates from Sorted List_Easy tag: Linked List

    Given a sorted linked list, delete all duplicates such that each element appear only once. Example 1 ...

  7. 算法与数据结构基础 - 链表(Linked List)

    链表基础 链表(Linked List)相比数组(Array),物理存储上非连续.不支持O(1)时间按索引存取:但链表也有其优点,灵活的内存管理.允许在链表任意位置上插入和删除节点.单向链表结构一般如 ...

  8. [LeetCode] 82. Remove Duplicates from Sorted List II_Medium tag: Linked List

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbe ...

  9. [LeetCode] Remove Linked List Elements 移除链表元素

    Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -- ...

随机推荐

  1. 使用pandas读取excel

    使用pandas读取excel Excel是微软的经典之作,在这里我们介绍使用Python的pandas数据分析包来解决此问题. pd.read_excel(io, sheet_name = 0, h ...

  2. kali apt update 错误——下列签名无效: EXPKEYSIG ED444FF07D8D0BF6 Kali Linux Repository

    这是因为key过期了 wget -q -O - https://archive.kali.org/archive-key.asc | apt-key add apt update

  3. python中numpy.concatenate()函数的使用

    numpy库数组拼接np.concatenate 原文:https://blog.csdn.net/zyl1042635242/article/details/43162031 思路:numpy提供了 ...

  4. 使用 TestFight 构建 Beta 测试版本

    ---恢复内容开始--- Beta测试属于软件开发周期中的一环,测试的重点就是让一些活生生的人去使用你的App,不断测试然后反馈.你需要让你的测试成员发现尽可能多的bug,以便你在公开发布之前将其修复 ...

  5. <audio>音频标签

    <audio ref="audio" @canplay="ready" @error="error"  @timeupdate=&qu ...

  6. Codeforces1301B. Motarack's Birthday

    题意是说给你一串数组,其中-1代表未知,求相邻两个数之差的绝对值最小,-1可以由k赋值,先考虑-1的情况,把k解出来,转换一下,就是绝对值之差最小情况,|k-a|,|k-b|,|k-c|,要使最大的最 ...

  7. html弹出框播放视频

    <a data-toggle="modal" data-target=".bs-example-modal-lg">模态框</a> &l ...

  8. 【剑指Offer面试编程题】题目1367:二叉搜索树的后序遍历序列--九度OJ

    题目描述: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. 输入: 每个测试案例包括2行: 第一行为1个整数 ...

  9. EJS 高效的 JavaScript 模板引擎

    什么是 EJS? "E" 代表 "effective",即[高效].EJS 是一套简单的模板语言,帮你利用普通的 JavaScript 代码生成 HTML 页面 ...

  10. PyQt5点击菜单栏弹出新窗口,解决新窗口闪退的实现方法

    实现的功能为:当点击菜单中某个菜单时,会弹出一个新窗口,下面就列出部分代码 def mail_setting(self): log.debug("open mail settings&quo ...