模板题目:LinkedList/PreSum(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.
就是说 一遍又一遍的遍历这个likedlist,删除所有的加和为0的子链 直到没有这种子链了 返回剩下的链就行。
这种求区间和的 想要快一点 就要用Presum array
但是就算这样 我们也要一遍一遍的遍历然后得到presum array.
我试着用这种思想去写了 但是行不通。
(写道删除linkedlist节点的时候才发现不太行)
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
List<Integer> deleteIndex = new ArrayList<>();
int length = 0;
List<Integer> preSum = new ArrayList<>();
preSum.add(0);
ListNode p = head;
while (p != null) {
length++;
preSum.add(preSum.get(preSum.size() - 1) + p.val);
p = p.next;
}
int i = 0;
int j = 0;
while (i < preSum.size() && j < preSum.size()) {
if (j == preSum.size()) { //when j reached the end, we have to re-initialize
i = deleteInedx.get(deleteIndex.size() - 1) + 1;
j = i + 1;
}
if (preSum.get(j) == preSum.get(i)) { //
deleteIndex.add(i + 1);//起始点是第i+1个
deleteIndex.add(j);//终点是第j个
}
j++;
}
//we are gonna delete the linkedlist according to deleteIndex;
//仔细想一下 这种方式实际上行不通 因为没有办法想list一样快速检索按照index区间删除list
}
}
看了一下答案 这代码的简介程度让我羞愧。
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
Map<Integer, ListNode> map = new HashMap<>(); //the current presum until this node
ListNode preHead = new ListNode(0); //我们为什么一定需要这个?因为我们的头结点是有可能最后删掉的哦
preHead.next = head;
int sum = 0;
ListNode p = preHead;
while (p != null) {
sum += p.val;
map.put(sum, p);
p = p.next;
}
sum = 0;
p = preHead; //re-initialize the p and sum
while (p != null) {
sum += p.val;
p.next = map.get(sum).next;//p是不包括的 但是我们包括了map.get(sum)
p = p.next;
}
return preHead.next;
}
}
尤其是这一步:
p.next = map.get(sum).next;
简直让我五体投地。
什么时候我也能写出这样思路清晰 明确简洁的代码呢?

浙公网安备 33010602011771号