LeetCode 1019. Next Greater Node In Linked List (链表中的下一个更大节点)
题目标签:Linked List, Stack
题目给了我们一个 Linked List,让我们找出对于每一个数字,它的下一个更大的数字。
首先把 Linked List 里的数字 存入 ArrayList, 方便后面的操作。
然后遍历 ArrayList,首先每一个数字,都会存入stack;所以就可以利用stack回到之前的数字,存入它的 next Greater Node。
Java Solution:
Runtime: 39 ms, faster than 65 %
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; } }
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步