"""
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. spring配置文件1

    applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?><beans xm ...

  2. 【原】openresty学习

    参考文档: 1.openresty最佳实践:https://moonbingbing.gitbooks.io/openresty-best-practices/content/ 2.openResty ...

  3. Android音频捕获(录音)(转)

    原文:http://www.yiibai.com/android/android_audio_capture.html Android有一个内置的麦克风,通过它可以捕获音频和存储,或在手机进行播放.有 ...

  4. eclipse问题集合

    [eclipse更换jdk版本]

  5. Spring MVC原理解析

    SpringMVC Spring MVC的工作原理 ①客户端的所有请求都交给前端控制器DispatcherServlet来处理,它会负责调用系统的其他模块来真正处理用户的请求. ② Dispatche ...

  6. QCMS代码审计:XSS+SQL+后台getshell

    qcms是一款比较小众的cms,最近更新应该是17年,代码框架都比较简单,但问题不少倒是... 网站介绍 QCMS是一款小型的网站管理系统.拥有多种结构类型,包括:ASP+ACCESS.ASP+SQL ...

  7. Redis的C++与JavaScript访问操作

    上篇简单介绍了Redis及其安装部署,这篇记录一下如何用C++语言和JavaScript语言访问操作Redis 1. Redis的接口访问方式(通用接口或者语言接口) 很多语言都包含Redis支持,R ...

  8. MyEclipse和Eclipse中常用的快捷键

    ##########################快捷键分类速查##########################     *******常用类********[Ctrl+O]   显示类中方法和 ...

  9. redhat 7.6 rpm ,yum ,编译安装

    rpm rpm  -ivh  包名  //安装 rpm  -e     包名   //卸载 which mount  查看命令安装目录 rpm  -qf    /usr/bin/mount    // ...

  10. Centos7 nginx 反向代理的配置

    一.正向代理与反向代理 1.正向代理 正向代理往VPN理解 正向代理,也就是传说中的代理,他的工作原理就像一个跳板(VPN),简单的说: 我是一个用户,我访问不了某网站,但是我能访问一个代理服务器,这 ...