[LeetCode] 1019. Next Greater Node In Linked List

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

链表中的下一个更大节点。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-node-in-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是单调栈(monotonic stack)。单调栈的定义是栈内所有元素是单调递增或者单调递减的。这个性质可以用来解决类似本题和239题。跟239题类似,本题往 stack 里面加入的依然是数字的 index 而不是数字本身。首先遍历 input,将链表的长度拿到,同时将链表里面节点的值放入一个 list。创建一个 stack 开始遍历 node 的值。分如下几种情况

  1. 如果栈为空,则直接加入当前节点的 index
  2. 如果栈不为空并且栈顶 index 背后指向的 val 小于当前节点的 val,则弹出栈顶元素并根据其本身的 index,放入 res 对应的位置;重复这个动作直到栈顶节点的 val 大于当前试图放入的节点的 val
  3. 如果栈不为空但是栈顶 index 背后指向的 val 大于当前节点的 val,则直接将当前节点的 index 加入栈;这样遍历完成后,栈底节点的 val 最大,栈顶节点的 val 最小

时间O(n^2), worse case

空间O(n)

Java实现

 1 class Solution {
 2     public int[] nextLargerNodes(ListNode head) {
 3         List<Integer> list = new ArrayList<>();
 4         for (ListNode node = head; node != null; node = node.next) {
 5             list.add(node.val);
 6         }
 7         int[] res = new int[list.size()];
 8         Stack<Integer> stack = new Stack<>();
 9         for (int i = 0; i < list.size(); i++) {
10             while (!stack.isEmpty() && list.get(stack.peek()) < list.get(i)) {
11                 res[stack.pop()] = list.get(i);
12             }
13             stack.push(i);
14         }
15         return res;
16     }
17 }

 

JavaScript实现

 1 /**
 2  * @param {ListNode} head
 3  * @return {number[]}
 4  */
 5 var nextLargerNodes = function (head) {
 6     let list = [];
 7     while (head != null) {
 8         list.push(head.val);
 9         head = head.next;
10     }
11     let res = new Array(list.length).fill(0);
12     let stack = [];
13     for (let i = 0; i < list.length; i++) {
14         while (stack.length > 0 && list[stack[stack.length - 1]] < list[i]) {
15             res[stack.pop()] = list[i];
16         }
17         stack.push(i);
18     }
19     return res;
20 };

 

单调栈相关题目

LeetCode 题目总结

posted @ 2020-03-14 09:13  CNoodle  阅读(237)  评论(0编辑  收藏  举报