From 66896e0d0554980c52d35d463bc4777247476912 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Fri, 5 Mar 2021 14:01:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9B=E6=89=A3=EF=BC=9A1171.=20=E4=BB=8E?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E4=B8=AD=E5=88=A0=E5=8E=BB=E6=80=BB=E5=92=8C?= =?UTF-8?q?=E5=80=BC=E4=B8=BA=E9=9B=B6=E7=9A=84=E8=BF=9E=E7=BB=AD=E8=8A=82?= =?UTF-8?q?=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../t20210305/RemoveZeroSumSublists.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 LeetCode/src/main/java/com/code/leet/study/t2021/t20210305/RemoveZeroSumSublists.java diff --git a/LeetCode/src/main/java/com/code/leet/study/t2021/t20210305/RemoveZeroSumSublists.java b/LeetCode/src/main/java/com/code/leet/study/t2021/t20210305/RemoveZeroSumSublists.java new file mode 100644 index 0000000..80858e4 --- /dev/null +++ b/LeetCode/src/main/java/com/code/leet/study/t2021/t20210305/RemoveZeroSumSublists.java @@ -0,0 +1,71 @@ +package com.code.leet.study.t2021.t20210305; + +import com.code.leet.entiy.ListNode; + +import java.util.HashMap; +import java.util.Map; + +/** + * 给你一个链表的头节点 head,请你编写代码,反复删去链表中由 总和 值为 0 的连续节点组成的序列,直到不存在这样的序列为止。 + *

+ * 删除完毕后,请你返回最终结果链表的头节点。 + *

+ *

+ *

+ * 你可以返回任何满足题目要求的答案。 + *

+ * (注意,下面示例中的所有序列,都是对 ListNode 对象序列化的表示。) + *

+ * 示例 1: + *

+ * 输入:head = [1,2,-3,3,1] + * 输出:[3,1] + * 提示:答案 [1,2,1] 也是正确的。 + * 示例 2: + *

+ * 输入:head = [1,2,3,-3,4] + * 输出:[1,2,4] + * 示例 3: + *

+ * 输入:head = [1,2,3,-3,-2] + * 输出:[1] + *

+ *

+ * 提示: + *

+ * 给你的链表中可能有 1 到 1000 个节点。 + * 对于链表中的每个节点,节点的值:-1000 <= node.val <= 1000. + */ +public class RemoveZeroSumSublists { + /** + * 1171. 从链表中删去总和值为零的连续节点 + */ + public ListNode removeZeroSumSublists(ListNode head) { + Map map = new HashMap<>(); + int sum = 0; + ListNode temp = head; + while (temp != null) { + sum += temp.val; + if (sum == 0 || map.containsKey(sum)) { + if (sum == 0) { + head = temp.next; + } else { + map.get(sum).next = temp.next; + } + if (head != null) { + map = new HashMap<>(); + temp = head; + sum = head.val; + } else { + return head; + } + } + while (temp.next != null && temp.next.val == 0) { + temp.next = temp.next.next; + } + map.put(sum, temp); + temp = temp.next; + } + return head; + } +}