leeetcode1171 Remove Zero Sum Consecutive Nodes from Linked List

时间:2024-08-25 20:34:38
 """
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]
"""