[LeetCode 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.

(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

时间: 2024-11-08 23:33:41

[LeetCode 1171] Remove Zero Sum Consecutive Nodes from Linked List的相关文章

leeetcode1171 Remove Zero Sum Consecutive Nodes from Linked List

1 """ 2 Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. 3 4 After doing so, return the head of the final linked list. You may return any such answer. 5 6

leetcode --day12 Surrounded Regions &amp; Sum Root to Leaf Numbers &amp; Longest Consecutive Sequence

1.  Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your fu

[leetcode笔记] Remove Duplicates from Sorted List II

问题描述: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,Given 1->2->3->3->4->4->5, return 1->2->5.Given 1->1->1->2->3, return 2-&

leetcode之Partition List,Reverse Nodes in k-Group

Partition List Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Give

LeetCode --- 64. Minimum Path Sum

题目链接:Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 这道题的要求是在m*n

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

leetcode 练习1 two sum

leetcode 练习1  two sum [email protected] 问题描述 Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15

LeetCode:Remove Nth Node From End of List

1.题目名称 Remove Nth Node From End of List(移除链表中倒数第n项) 2.题目地址 https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 3.题目内容 英文:Given a linked list, remove the nth node from the end of list and return its head. 中文:给出一个链表,删去链表中的倒数第n项,返回链表首节点 例如:

【LeetCode】Remove Duplicates from Sorted Array 解题报告

[LeetCode]Remove Duplicates from Sorted Array 解题报告 标签(空格分隔): LeetCode [LeetCode] https://leetcode.com/problems/remove-duplicates-from-sorted-array/ Total Accepted: 129010 Total Submissions: 384622 Difficulty: Easy Question Given a sorted array, remov