【算法】【单调栈】【leetcode】1019. 链表中的下一个更大节点

刷这题之前先看:

【算法】【OD算法】【单调栈】找朋友-CSDN博客

【算法】【单调栈】【leetcode】1475. 商品折扣后的最终价格-CSDN博客 

【算法】【单调栈】【leetcode】901. 股票价格跨度-CSDN博客 

【算法】【单调栈】每日温度-CSDN博客 

题目地址:. - 力扣(LeetCode)

题目描述:

给定一个长度为 n 的链表 head

对于列表中的每个节点,查找下一个 更大节点 的值。也就是说,对于每个节点,找到它旁边的第一个节点的值,这个节点的值 严格大于 它的值。

返回一个整数数组 answer ,其中 answer[i] 是第 i 个节点( 从1开始 )的下一个更大的节点的值。如果第 i 个节点没有下一个更大的节点,设置 answer[i] = 0 。

示例 1:

输入:head = [2,1,5]
输出:[5,5,0]

示例 2:

输入:head = [2,7,4,3,5]
输出:[7,0,5,5,0]

提示:

  • 链表中节点数为 n
  • 1 <= n <= 104
  • 1 <= Node.val <= 109

代码实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int[] nextLargerNodes(ListNode head) {
        //栈中存放数组下标和值 0->值 1->坐标
        Stack<Integer[]> st = new Stack();
        int [] temp = new int [10*10*10*10];
        Integer len=0;
        while(null != head){
            while(!st.isEmpty()&&st.peek()[0]<head.val){
                temp[st.pop()[1]]=head.val;
            }
            st.push(new Integer[]{head.val,len++});
            head=head.next;
        }
        int [] ans = new int[len];
        for(int i=0; i<len;i++){
            ans[i]=temp[i];
        }
        return ans;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值