• 【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.

    解题思路:方法比较简单,可以从头开始遍历链表,并累加每一个节点的和,遇到和为零或者与之前出现过的和相同的情况则表示这一段可以删除,删除后又重头开始遍历链表,直到找不到可以删除的段为止。至于怎么删除链表的中一段,我的方法是用一个list保存链表的所有节点,删除的时候直接删除list的元素。全部删除完成后再将list的剩余元素组成新链表即可。

    代码如下:

    # Definition for singly-linked list.
    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution(object):
        def removeZeroSumSublists(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            node_list = []
            node = head
            while node != None:
                node_list.append(node)
                node = node.next
    
            flag = True
            while flag:
                flag = False
                dic = {}
                amount = 0
                for inx,item in enumerate(node_list):
                    amount += item.val
                    if amount == 0:
                        node_list = node_list[inx+1:]
                        flag = True
                        break
                    elif amount in dic:
                        node_list = node_list[:dic[amount] + 1] + node_list[inx + 1:]
                        flag = True
                        break
                    dic[amount] = inx
            if len(node_list) == 0:
                return None
            for i in range(len(node_list)-1):
                node_list[i].next = node_list[i+1]
            node_list[-1].next = None
            head = node_list[0]
            return head
  • 相关阅读:
    An unhandled exception occurred while processing the request.
    PIP升级或更新、PIP 升级 或 更新 失败
    SQL求两个时间差
    EF Core DBFirst 和Code First小结
    Core + Vue 后台管理基础框架9——统一日志
    .Net Core 访问 appsettings.json
    IdentityServer4 (5) 混合模式(Hybrid)
    C# async/await、WhenAll、ContinueWith 实战应用(异步做早餐)
    .NET Core Web APi FormData多文件上传,IFormFile强类型文件灵活绑定
    Unity3D天气系统插件UniStorm插件使用说明
  • 原文地址:https://www.cnblogs.com/seyjs/p/11440723.html
Copyright © 2020-2023  润新知