leeetcode1171 Remove Zero Sum Consecutive Nodes from Linked List

  1 """
  2 Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
  3
  4 After doing so, return the head of the final linked list.  You may return any such answer.
  5
  6
  7
  8 (Note that in the examples below, all sequences are serializations of ListNode objects.)
  9
 10 Example 1:
 11
 12 Input: head = [1,2,-3,3,1]
 13 Output: [3,1]
 14 Note: The answer [1,2,1] would also be accepted.
 15
 16 Example 2:
 17
 18 Input: head = [1,2,3,-3,4]
 19 Output: [1,2,4]
 20
 21 Example 3:
 22
 23 Input: head = [1,2,3,-3,-2]
 24 Output: [1]
 25
 26 """
 27 class ListNode(object):
 28     def __init__(self, x):
 29         self.val = x
 30         self.next = None
 31
 32 class Solution1(object):
 33     def removeZeroSumSublists(self, head):
 34         """
 35         :param head: ListNode
 36         :return: ListNode
 37         """
 38         if not head.next:
 39             return head if head.val != 0 else None  #判断头节点是为否为空
 40         list = []   #建立list存储链表转化后的数组
 41         p = head    #建立p指针指向头结点
 42         while(p):   #将链表转为数组
 43             list.append(p.val)
 44             p = p.next
 45         list = self.remove(list)  #!!!删除连续和为0
 46         newhead = ListNode(-1)    #建立新的头结点
 47         p = newhead               #p指向新的头结点
 48         for num in list:          #将结果数组转成链表
 49             p.next = ListNode(num)
 50             p = p.next
 51         return newhead.next
 52     """
 53     在一个数组里把连续和为0的部分删除,两层循环:用i对每个元素遍历
 54     再用j不断的对当前子数组求和,若为0,删除当前部分并进行递归
 55     """
 56     def remove(self, list):       #在一个数组里把连续和为0的部分删除
 57         for i in range(len(list)):
 58             sum = list[i]
 59             j = i + 1
 60             while(j <= len(list)):
 61                 if sum == 0:
 62                     return self.remove(list[:i] + list[j:])   #递归处理
 63                 else:
 64                     if j == len(list):
 65                         break
 66                     sum += list[j]
 67                     j += 1
 68         return list
 69
 70 """
 71 用一个变量pre_sum记录前缀和,再用一个哈希表记录出现过的前缀和,
 72 如果出现了两个相同的前缀和,就说明中间这一段的和为0,是多余的。
 73 举例:
 74 对于输入 [1, 2, -2, 3, -1, -1, -1],
 75 前缀和为[1, 3, 1, 4, 3, 2, 1],
 76 下标为0的1和下标为2的1相同,
 77 就代表下标在【1, 2】间的元素的和为0。
 78 """
 79 class Solution2(object):
 80     def removeZeroSumSublists(self, head):
 81         """
 82         :param head: ListNode
 83         :return: ListNode
 84         """
 85         dummy = ListNode(-1) #用一个假头结点dummy返回结果,
 86         dummy.next = head    #防止头节点head被删除无法返回
 87         pre_sum = 0          #记录前缀和
 88         record = {0: dummy}  # 用dict来存出现过的每个前缀和
 89         # bug代码record = {0,dummy} 这里需要对record初始化{:}
 90         while head:
 91             pre_sum += head.val  # bug代码 马虎没有写‘+‘
 92             if pre_sum in record:
 93                 record[pre_sum].next = head.next #寻找是否有重复的元素
 94             else:                                #类似于leetcode1:twoSum
 95                 record[pre_sum] = head
 96             head = head.next
 97         return dummy.next    #用dummy来返回结果
 98 """
 99 Wrong answer
100 Input
101 [1,3,2,-3,-2,5,5,-5,1]
102 Output
103 [1,5,5,-5,1]
104 Expected
105 [1,5,1]
106 """

原文地址:https://www.cnblogs.com/yawenw/p/12250481.html

时间: 2024-11-04 13:52:33

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 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 example

[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 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing. Notice You sh

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 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing. Notice You sh

lintcode-medium-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 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing. Notice You sh

LintCode &quot;Swap Two Nodes in Linked List&quot;

Nothing special. Just take care of corner cases. class Solution { public: /** * @param head a ListNode * @oaram v1 an integer * @param v2 an integer * @return a new head of singly-linked list */ ListNode* swapNodes(ListNode* head, int v1, int v2) { i

[GeeksForGeeks] Remove all half nodes of a given binary tree

Given A binary Tree, how do you remove all the half nodes (which has only one child)? Note leaves should not be touched as they have both children as NULL. For example consider the below tree. Nodes 7, 5 and 9 are half nodes as one of their child is

数据结构:单向链表(Linked List)

本文来源: Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Linked List | Set 3 (Deleting a node) Find Length of a Linked List (Iterative and Recursive) (todo:在结构中保持节点数信息) Search an element in a Linked List (Iterative and Recursiv

一份来自于全球的前端面试题清单,看看老外喜欢考哪些题(部分有答案)

方括号中的蓝色标题是题目的出处,有些题目在原址内包含答案.搜集的大部分外国前端面试题没有做翻译,单词并不难,大家应该看得懂.题目旁边的方括号内, 简单记录了与此题相关的知识点.总共大概一千多道,包含国内的题目,如有错误,欢迎指正.有些原链可能已无法打开,有些可能需要代理才能查看. 一.HTML [HTML related interview questions] 1.What is doctype? Why do u need it? 2.What is the use of data-* at

LintCode链表题总结

由于链表本身结构的单一性,链表的题目很少会有很大的变种,基本都是围绕几个基本的考点出题目.所以链表的题目比较好掌握,但是链表的题目又不太容易一次就AC通过,由于边界情况未考虑.空指针(比如head.next不存在但是却给head.next赋值了,就会抛出nullpointer的错误).越界等边界情况,我们需要在测试用例的时候多考虑边界条件.在模拟计算的时候一定要用纸和笔把中间的操作过程给画出来,这样比较容易形成思路. 在LintCode的ladder1中,链表那一章有如下这一些题目: 此外,Li