Leetcode--1019. 链表中的下一个更大节点(java)
給出一個以頭節點?head?作為第一個節點的鏈表。鏈表中的節點分別編號為:node_1, node_2, node_3, ... 。
每個節點都可能有下一個更大值(next larger value):對于?node_i,如果其?next_larger(node_i)?是?node_j.val,那么就有?j > i?且??node_j.val > node_i.val,而?j?是可能的選項中最小的那個。如果不存在這樣的?j,那么下一個更大值為?0?。
返回整數答案數組?answer,其中?answer[i] = next_larger(node_{i+1})?。
注意:在下面的示例中,諸如 [2,1,5] 這樣的輸入(不是輸出)是鏈表的序列化表示,其頭節點的值為?2,第二個節點值為 1,第三個節點值為?5 。
?
示例 1:
輸入:[2,1,5]
輸出:[5,5,0]
示例 2:
輸入:[2,7,4,3,5]
輸出:[7,0,5,5,0]
示例 3:
輸入:[1,7,5,1,9,2,5,1]
輸出:[7,9,9,9,0,5,0,0]
?
提示:
對于鏈表中的每個節點,1 <= node.val?<= 10^9
給定列表的長度在 [0, 10000]?范圍內
通過次數7,986提交次數14,693
代碼:
/**
?*?Definition?for?singly-linked?list.
?*?public?class?ListNode?{
?*?????int?val;
?*?????ListNode?next;
?*?????ListNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????public?int[]?nextLargerNodes(ListNode?head)?{
????????List<Integer>?res?=?new?ArrayList<>();
????????Stack<Integer>?stack?=?new?Stack<>();
????????List<Integer>?data?=?new?ArrayList<>();
????????int?index=0;
????????while(head!=null){
????????????res.add(0);
????????????data.add(head.val);
????????????while(!stack.isEmpty()&&head.val>data.get(stack.peek())){
????????????????res.set(stack.pop(),head.val);
????????????}
????????????stack.push(index);
????????????index++;
????????????head?=?head.next;
????????}
????????int?arr[]?=?new?int[res.size()];
????????for(int?i=0;i<arr.length;i++){
????????????arr[i]?=?res.get(i);
????????}
????????return?arr;
????}
}
總結
以上是生活随笔為你收集整理的Leetcode--1019. 链表中的下一个更大节点(java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【剑指offer】面试题45:把数组排成
- 下一篇: Leetcode--342. 4的幂