"""
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. 学习笔记(11)- 文本生成RNNLG

    https://github.com/shawnwun/RNNLG 数据集 给出了4个行业的语料,餐馆.酒店.电脑.电视,及其组合数据. 数据格式 任务 根据给定格式的命令,生成自然语言. 方法.模型 ...

  2. run jumper server

    1. 生成key: $ if [ "$SECRET_KEY" = "" ]; then SECRET_KEY=`cat /dev/urandom | tr -d ...

  3. 学习java时在要求输出的数字带俩个小数点时,利用String.format时出现的问题

    public class StringFormatDemo { public static void main(String[] args) { //String.format 实现了四舍五入 Sys ...

  4. SystemVerilog for design 笔记(二)

    转载请标明出处 1. System Verilog文本值和数据类型 1.1. 增强的文本值赋值 相对于verilog,SV在文本值赋值时可以1.无需指定进制    2.赋值可以是逻辑1 用法: reg ...

  5. 在ng-repeat 中使用 ng-click

    angular 中使用 ng-repeat  过程中,有时需要绑定 事件 click ,使用ng-click ,但是并没有效果,此时应该使用 data-ng-click 替代 ng-click ,并且 ...

  6. CSP-S 2019 初赛游记

    Day 0 上午考了一套毒瘤的数据结构题,考的我心态爆炸SB出题人 晚上考了一套初赛模拟,只考1h,然后我91分,感觉初赛完全没问题? 回寝室后一直在忙活,整理东西什么的,居然将近12点睡? Day ...

  7. linux 从一台服务器向另台服务器复制文件

    使用scp命令: sudo scp -P 2222 username@192.168.0.200:/home/db/db_data.sql.gz /home/db/db_data.sql.gz scp ...

  8. 笔记||Python3进阶之调用外部程序

    像wget可以下载文件 ffmpeg可以切割.合并.转换.录制视频 free命令可以查看linux内存使用信息 python提供了库来调用外部程序.命令?> 最常见的两种方法:       ①o ...

  9. Random Variables

    可测空间(Measurable Space)和测度空间(Measure Space) 集合X,X上的一个σ-algebra A,则(X,A)被称为可测空间(measurable space) 再在A上 ...

  10. spyder崩溃修复

    实验室突然断电,重启电脑后spyder崩溃 在anaconda命令行中输入命令失败 StackOverflow上找的解决方案,适合win10系统,简单粗暴 在win10搜索里面找,点一下就自动修复了