leeetcode1171 Remove Zero Sum Consecutive Nodes from Linked List
"""
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的更多相关文章
- 【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 ...
- 【LeetCode】1171. Remove Zero Sum Consecutive Nodes from Linked List 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 preSum + 字典 日期 题目地址:https:/ ...
- [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 ...
- 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 ...
- LintCode "Swap Two Nodes in Linked List"
Nothing special. Just take care of corner cases. class Solution { public: /** * @param head a ListNo ...
- [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 ...
- 算法与数据结构基础 - 链表(Linked List)
链表基础 链表(Linked List)相比数组(Array),物理存储上非连续.不支持O(1)时间按索引存取:但链表也有其优点,灵活的内存管理.允许在链表任意位置上插入和删除节点.单向链表结构一般如 ...
- [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 ...
- [LeetCode] Remove Linked List Elements 移除链表元素
Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -- ...
随机推荐
- Spark入门:第2节 Spark集群安装:1 - 3;第3节 Spark HA高可用部署:1 - 2
三. Spark集群安装 3.1 下载spark安装包 下载地址spark官网:http://spark.apache.org/downloads.html 这里我们使用 spark-2.1.3-bi ...
- [libpng]CMake+VS2015下编译libpng,及使用小例
编译前的工作 在编译libpng前,需要把zlib编译好,并加载到编译环境里. CMake + VS2015 下编译zlib,及使用小例 下载与解压 libpng的官网是 http://www.lib ...
- 「ZJOI2013」K大数查询
「ZJOI2013」K大数查询 传送门 整体二分,修改的时候用线段树代替树状数组即可. 参考代码: #include <cstdio> #define rg register #defin ...
- Python的类(class)和实例(Instance)如何操作使用
面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可 ...
- 如何用python写个人专属群聊提醒小助手?
前言 大家还记得教会父母玩微信是什么时候吗?父母学会后,我们的生活就发生了「质」的变化,父母也许会吐槽你的微信头像不好,要你换一个头像. 最近 pk哥 又被母后大人吐槽了,原因是亲戚微信群里某个亲戚生 ...
- 学术Essay写作简单且稳定的架构解析
学术essay写作(academic writing),无论是论文还是专著,间架要稳固,才有可读性,才有说服力. 稳,有几个应然特征:部块(parts)关联紧密:部块不外生枝叶:部块之间没有杂质干扰. ...
- 【快学springboot】5.全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- [转]网络协议-redis协议
Redis 通信协议(protocol) 本文档翻译自: http://redis.io/topics/protocol . Redis 协议在以下三个目标之间进行折中: 易于实现 可以高效地被计算机 ...
- A. Optimal Currency Exchange 兑换硬币,剩下的钱最少
A. Optimal Currency Exchange time limit per test 1.5 seconds memory limit per test 512 megabytes inp ...
- Oracle 提取数据表信息
参考: https://www.progress.com/blogs/jdbc-tutorial-extracting-database-metadata-via-jdbc-driver http:/ ...