返回介绍

solution / 1100-1199 / 1171.Remove Zero Sum Consecutive Nodes from Linked List / README_EN

发布于 2024-06-17 01:03:22 字数 7181 浏览 0 评论 0 收藏 0

1171. Remove Zero Sum Consecutive Nodes from Linked List

中文文档

Description

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 and 1000 nodes.
  • Each node in the linked list has -1000 <= node.val <= 1000.

Solutions

Solution 1: Prefix Sum + Hash Table

If two prefix sums of the linked list are equal, it means that the sum of the continuous node sequence between the two prefix sums is $0$, so we can remove this part of the continuous nodes.

We first traverse the linked list and use a hash table $last$ to record the prefix sum and the corresponding linked list node. For the same prefix sum $s$, the later node overwrites the previous node.

Next, we traverse the linked list again. If the current node $cur$ has a prefix sum $s$ that appears in $last$, it means that the sum of all nodes between $cur$ and $last[s]$ is $0$, so we directly modify the pointer of $cur$ to $last[s].next$, which removes this part of the continuous nodes with a sum of $0$. We continue to traverse and delete all continuous nodes with a sum of $0$.

Finally, we return the head node of the linked list $dummy.next$.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list.

# Definition for singly-linked list.
# class ListNode:
#   def __init__(self, val=0, next=None):
#     self.val = val
#     self.next = next
class Solution:
  def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
    dummy = ListNode(next=head)
    last = {}
    s, cur = 0, dummy
    while cur:
      s += cur.val
      last[s] = cur
      cur = cur.next
    s, cur = 0, dummy
    while cur:
      s += cur.val
      cur.next = last[s].next
      cur = cur.next
    return dummy.next
/**
 * 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> last = new HashMap<>();
    int s = 0;
    ListNode cur = dummy;
    while (cur != null) {
      s += cur.val;
      last.put(s, cur);
      cur = cur.next;
    }
    s = 0;
    cur = dummy;
    while (cur != null) {
      s += cur.val;
      cur.next = last.get(s).next;
      cur = cur.next;
    }
    return dummy.next;
  }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *   int val;
 *   ListNode *next;
 *   ListNode() : val(0), next(nullptr) {}
 *   ListNode(int x) : val(x), next(nullptr) {}
 *   ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
  ListNode* removeZeroSumSublists(ListNode* head) {
    ListNode* dummy = new ListNode(0, head);
    unordered_map<int, ListNode*> last;
    ListNode* cur = dummy;
    int s = 0;
    while (cur) {
      s += cur->val;
      last[s] = cur;
      cur = cur->next;
    }
    s = 0;
    cur = dummy;
    while (cur) {
      s += cur->val;
      cur->next = last[s]->next;
      cur = cur->next;
    }
    return dummy->next;
  }
};
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *   Val int
 *   Next *ListNode
 * }
 */
func removeZeroSumSublists(head *ListNode) *ListNode {
  dummy := &ListNode{0, head}
  last := map[int]*ListNode{}
  cur := dummy
  s := 0
  for cur != nil {
    s += cur.Val
    last[s] = cur
    cur = cur.Next
  }
  s = 0
  cur = dummy
  for cur != nil {
    s += cur.Val
    cur.Next = last[s].Next
    cur = cur.Next
  }
  return dummy.Next
}
/**
 * Definition for singly-linked list.
 * class ListNode {
 *   val: number
 *   next: ListNode | null
 *   constructor(val?: number, next?: ListNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 *   }
 * }
 */

function removeZeroSumSublists(head: ListNode | null): ListNode | null {
  const dummy = new ListNode(0, head);
  const last = new Map<number, ListNode>();
  let s = 0;
  for (let cur = dummy; cur; cur = cur.next) {
    s += cur.val;
    last.set(s, cur);
  }
  s = 0;
  for (let cur = dummy; cur; cur = cur.next) {
    s += cur.val;
    cur.next = last.get(s)!.next;
  }
  return dummy.next;
}
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//   ListNode {
//     next: None,
//     val
//   }
//   }
// }
impl Solution {
  pub fn remove_zero_sum_sublists(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let dummy = Some(Box::new(ListNode { val: 0, next: head }));
    let mut last = std::collections::HashMap::new();
    let mut s = 0;
    let mut p = dummy.as_ref();
    while let Some(node) = p {
      s += node.val;
      last.insert(s, node);
      p = node.next.as_ref();
    }

    let mut dummy = Some(Box::new(ListNode::new(0)));
    let mut q = dummy.as_mut();
    s = 0;
    while let Some(cur) = q {
      s += cur.val;
      if let Some(node) = last.get(&s) {
        cur.next = node.next.clone();
      }
      q = cur.next.as_mut();
    }
    dummy.unwrap().next
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文