Skip to content

Commit c9719fe

Browse files
committed
Time: 2 ms (94.41%), Space: 43.7 MB (32.94%) - LeetHub
1 parent 01a1134 commit c9719fe

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode removeZeroSumSublists(ListNode head) {
13+
ListNode dummy = new ListNode(0, head);
14+
int prefix = 0;
15+
Map<Integer, ListNode> prefixToNode = new HashMap<>();
16+
prefixToNode.put(0, dummy);
17+
18+
for (; head != null; head = head.next) {
19+
prefix += head.val;
20+
prefixToNode.put(prefix, head);
21+
}
22+
23+
prefix = 0;
24+
25+
for (head = dummy; head != null; head = head.next) {
26+
prefix += head.val;
27+
head.next = prefixToNode.get(prefix).next;
28+
}
29+
30+
return dummy.next;
31+
}
32+
}

0 commit comments

Comments
 (0)