LeetCode 1019. Next Greater Node In Linked List 解题报告(python)

1019. Next Greater Node In Linked List

  1. Next Greater Node In Linked List python solution

题目描述

We are given a linked list with head as the first node. Let’s number the nodes in the list: node_1, node_2, node_3, … etc.

Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0.

Return an array of integers answer, where answer[i] = next_larger(node_{i+1}).

Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.
在这里插入图片描述

解析

题目的意思是,给定单链表,我们需要找到每个节点后面第一个比它大的元素。如果不存在就为0。将这些元素组成一个新的序列并返回。

为了保证数列的相对位置不变,我们使用栈来进行操作。需要保存两种信息,第一个是该元素所在位置,第二个是该元素的大小。

如果遇到了一个数字n比栈顶元素stack[-1]为下标的数字更大时,需要一直退栈,这样就保证不会被多次更新,只记录第一个比自己大的元素。退栈到栈顶元素大于等于目前元素为止。

res数组记录最终结果,然后stack栈作为更新的指引,避免更新过的元素被二次更新,从而保证只记录第一个比自己大的元素。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def nextLargerNodes(self, head):
        res,stack=[],[]
        while head:
            while stack and stack[-1][1]<head.val:
                res[stack.pop()[0]]=head.val
            stack.append([len(res),head.val])
            res.append(0)
            head=head.next
        return res

Reference

https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/265508/JavaC%2B%2BPython-Next-Greater-Element

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值