[LeetCode 1171] Remove Zero Sum Consecutive Nodes from Linked List

本文介绍了一种算法,用于删除链表中连续节点和为0的子序列,直至链表中不再存在这样的序列。提供了两种解决方案:一种使用双指针实现O(N^2)的时间复杂度;另一种利用前缀和与哈希映射实现O(N)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

 

Solution 1. Two pointers, O(N^2) runtime, O(1) space

1. Have a left and right pointer l and r; Also init a pointer called prevL that is the previous node of l.

2. start l with the first node, move r one node at a time. For each node that r is visiting, there will be the following 2 cases.

a. if the running sum is 0, delete all nodes from l to r inclusively by setting the next pointer of prevL to r's next node. Then update l to r.

b. else, update prevL to l.

3. move l to its next node and repeat step 2 until l reaches the end of the linked list.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeZeroSumSublists(ListNode head) {
        ListNode dummy = new ListNode(1000 * 1000 + 1);
        dummy.next = head;
        ListNode prevL = dummy, l = head, r = head;
        
        while(l != null) {
            r = l;
            int sum = 0;
            boolean skip = false;
            while(r != null) {
                sum += r.val;
                if(sum == 0) {  
                    prevL.next = r.next;
                    l = r;
                    skip = true;
                    break;
                }
                r = r.next;
            }
            if(!skip) {
                prevL = l;
            }            
            l = l.next;
        }
        return dummy.next;
    }
}

 

 

Solution 2. Prefix Sum with HashMap, O(N) runtime and space

1. Create a dummy node of value 0 and a hashmap that maps prefixsum to node.

2. Starting from the dummy node, compute prefix sum that ends at the current node.

If there already exists a prefix sum of the same value in the hashmap, we know all nodes from map.get(prefixSum).next to the current node(inclusive) sum to 0. Delete all these nodes by map.get(prefixSum).next = curr.next.  Since these nodes are deleted, we need to remove all the prefix sums that end at these deleted nodes from the map. 

Else, put the current prefix sum and node to the map for later checks.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeZeroSumSublists(ListNode head) {
        ListNode dummy = new ListNode(0), curr = dummy;
        Map<Integer, ListNode> map = new HashMap<>();
        dummy.next = head;
        int prefixSum = 0;
        while(curr != null) {
            prefixSum += curr.val;
            if(map.containsKey(prefixSum)) {
                ListNode node = map.get(prefixSum).next;
                int sum = prefixSum;
                while(node != curr) {
                    sum += node.val;
                    map.remove(sum);
                    node = node.next;
                }
                map.get(prefixSum).next = curr.next;
            }
            else {
                map.put(prefixSum, curr);
            }
            curr = curr.next;
        }
        return dummy.next;
    }
}

 

转载于:https://www.cnblogs.com/lz87/p/11605711.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值