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]
Constraints:
- The given linked list will contain between
1
and1000
nodes. - Each node in the linked list has
-1000 <= node.val <= 1000
.
题目链接:https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/
题目大意:删除链表中连续和为0的节点段
题目分析:链表新转数组,求前缀和,滤掉前缀和为0的最长前缀,后面部分若前缀和相同,则区间段和为0,跳过这部分,注意0必然不在答案数组中,最后将答案数组转为链表(写的好丑)
2ms,时间击败79.64%
/**
* 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 int getListLen(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}
public ListNode removeZeroSumSublists(ListNode head) {
int n = getListLen(head);
int[] nums = new int[n];
for (int i = 0; i < n; i++){
nums[i] = head.val;
head = head.next;
}
int[] presum = new int[n];
presum[0] = nums[0];
int sti = 0;
for (int i = 1; i < n; i++) {
presum[i] = presum[i - 1] + nums[i];
if (presum[i] == 0) {
sti = i + 1;
}
}
if (presum[n - 1] == 0) {
return null;
}
int[] ans = new int[n];
int cnt = 0;
for (int i = sti; i < n; i++) {
boolean find = false;
for (int j = n - 1; j > i; j--) {
if (presum[i] == presum[j]) {
if (nums[i] != 0) {
ans[cnt++] = nums[i];
}
i = j;
find = true;
break;
}
}
if (!find && nums[i] != 0) {
ans[cnt++] = nums[i];
}
}
if (cnt == 0) {
return null;
}
ListNode helper = new ListNode(ans[0]);
ListNode res = helper;
for (int i = 1; i < cnt; i++) {
helper.next = new ListNode(ans[i]);
helper = helper.next;
}
return res;
}
}