LeetCode每日一题(1019. Next Greater Node In Linked List)

本文介绍了一种算法,用于解决链表中每个节点找到其下一个更大节点的问题。通过使用递归方法配合栈的数据结构,可以高效地计算出每个节点右侧第一个严格更大的节点值。若不存在则设置为0。

You are given the head of a linked list with n nodes.

For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.

Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

Example 1:

Input: head = [2,1,5]
Output: [5,5,0]

Example 2:

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 104
  • 1 <= Node.val <= 109

维护一个单调递减的栈, 用来表示后面节点的最大值情况, 如果当前节点的值小于栈顶的值, 则 pop, 直到遇到比当前值大的值, 该值即当前值右侧第一个大于它的值。



impl Solution {
    fn rc(head: Option<Box<ListNode>>, ans: &mut Vec<i32>) -> Vec<i32> {
        if let Some(mut node) = head {
            let mut l = Solution::rc(node.next.take(), ans);
            while let Some(v) = l.pop() {
                if v > node.val {
                    l.push(v);
                    break;
                }
            }
            ans.push(if l.is_empty() { 0 } else { *l.last().unwrap() });
            l.push(node.val);
            return l;
        }
        Vec::new()
    }
    pub fn next_larger_nodes(head: Option<Box<ListNode>>) -> Vec<i32> {
        let mut ans = Vec::new();
        Solution::rc(head, &mut ans);
        ans.reverse();
        ans
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值