LeetCode 1019 Next Greater Node In Linked List (单调栈)

244 篇文章 0 订阅
129 篇文章 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

题目链接:https://leetcode.com/problems/next-greater-node-in-linked-list/

题目大意:求链表每个值之后比它大的值

题目分析:单调栈模拟一下,需要记录进站的顺序

5ms,时间击败98.95%

/**
 * 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 {
    
    class Val {
        int pos, val;
        Val(int p, int v) {
            this.pos = p;
            this.val = v;
        }
    }

    private int getLen(ListNode head) {
        int ans = 0;
        while(head != null) {
            head = head.next;
            ans++;
        }
        return ans;
    }
    
    public int[] nextLargerNodes(ListNode head) {
        int n = getLen(head);
        int[] ans = new int[n];
        Val[] stk = new Val[n + 1];
        int top = 0, i = 0;
        stk[++top] = new Val(i, head.val);
        while (head.next != null) {
            i++;
            int nxtVal = head.next.val;
            if (nxtVal <= stk[top].val) {
                stk[++top] = new Val(i, nxtVal);
            } else {
                while (top > 0 && stk[top].val < nxtVal) {
                    ans[stk[top].pos] = nxtVal;
                    top--;
                }
                stk[++top] = new Val(i, nxtVal);
            }
            head = head.next;
        }
        while (top > 0) {
            ans[stk[top--].pos] = 0;
        }
        return ans;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值