LeetCode 1019. Next Greater Node In Linked List (链表中的下一个更大节点)

匿名 (未验证) 提交于 2019-12-02 23:47:01

题目标签:Linked List, Stack

  题目给了我们一个 Linked List,让我们找出对于每一个数字,它的下一个更大的数字。

  首先把 Linked List 里的数字 存入 ArrayList, 方便后面的操作。

  然后遍历 ArrayList,首先每一个数字,都会存入stack;所以就可以利用stack回到之前的数字,存入它的 next Greater Node。

Java Solution:

Memory Usage: 40 MB, less than 95 %

完成日期:05/06/2019

关键点:利用stack

/**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode(int x) { val = x; }  * }  */ class Solution {     public int[] nextLargerNodes(ListNode head) {                  ArrayList<Integer> nums = new ArrayList<>();         Stack<Integer> stack = new Stack<>();         int [] res;                  // save all numbers into ArrayList         for(ListNode node = head; node != null; node = node.next)             nums.add(node.val);                  res = new int[nums.size()];                  // use stack to find next greater element         for(int i=0; i<nums.size(); i++)         {             // once find a greater num, it will check all previous numbers in stack             while(!stack.isEmpty() && nums.get(stack.peek()) < nums.get(i))                   res[stack.pop()] = nums.get(i);                          stack.push(i); // save index into stack         }                  return res;     } }

参考资料:Le'e'tCode Discuss

LeetCode Questions List

题目来源:https://leetcode.com/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!