LeetCode1019-链表中的下一个更大节点

题目链接

英文链接:https://leetcode.com/problems/next-greater-node-in-linked-list/

中文链接:https://leetcode-cn.com/problems/next-greater-node-in-linked-list/

题目详述

给出一个以头节点 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:

1
2
输入:[2,1,5]
输出:[5,5,0]

示例 2:

1
2
输入:[2,7,4,3,5]
输出:[7,0,5,5,0]

示例 3:

1
2
输入:[1,7,5,1,9,2,5,1]
输出:[7,9,9,9,0,5,0,0]

提示:

  1. 对于链表中的每个节点,1 <= node.val <= 10^9
  2. 给定列表的长度在 [0, 10000] 范围内

题目详解

下一个更大:这种类型题目运用单调栈解答即可。类似还有以下题目:

为了方便操作,可以把链表转化为数组再进行解答。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LeetCode_01019 {

public int[] nextLargerNodes(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int[] res = new int[list.size()];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < list.size(); ++i) {
while (!stack.isEmpty() && list.get(i) > list.get(stack.peek())) {
res[stack.pop()] = list.get(i);
}
stack.push(i);
}
return res;
}
}

也可以直接在链表上进行操作,不过这时候需要我们自己记录下标信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LeetCode_01019 {

public int[] nextLargerNodes(ListNode head) {
int n = getLength(head);
int[] res = new int[n];
int i = 0;
Deque<int[]> stack = new ArrayDeque<>();
for (; head != null; head = head.next, ++i) {
while (!stack.isEmpty() && head.val > stack.peek()[0]) {
res[stack.pop()[1]] = head.val;
}
stack.push(new int[]{head.val, i});
}
return res;
}

private int getLength(ListNode head) {
int res = 0;
while (head != null) {
++res;
head = head.next;
}
return res;
}
}