zoukankan      html  css  js  c++  java
  • [LeetCode] 1019. Next Greater Node In Linked List

    链表中的下一个更大节点。题意是给一个linkedlist,请返回当前节点之后所有节点里面值最大的节点。注意最后一个节点之后因为没有其他节点了,所以返回0。例子,

    Example 1:

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

    Example 2:

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

    Example 3:

    Input: [1,7,5,1,9,2,5,1]
    Output: [7,9,9,9,0,5,0,0]

    思路是单调栈(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 题目总结

  • 相关阅读:
    yii之behaviors
    查看windows系统信息
    idm chrome扩展被阻止解决办法
    音乐乐理基础
    bootstrap4
    七牛上传整合CI
    提升上传速度
    卡漫绘图
    指针的操作
    定语从句八个易混淆
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12490559.html
Copyright © 2011-2022 走看看