LC.P1171[从链表中删去总和值为零的连续节点]

方法一:前缀和+哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
ListNode dummy = new ListNode(0, head);
Map<Integer, ListNode> map = new HashMap<>();
int sum = 0;
ListNode p = dummy;
while (p != null) {
sum += p.val;
map.put(sum, p);
p = p.next;
}
sum = 0;
p = dummy;
while (p != null) {
sum += p.val;
p.next = map.get(sum).next;
p = p.next;
}
return dummy.next;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$