题目描述

思路
- 本质:求数组中第一个大于某数字的数字的索引。
- 方法一:TC O(N^2), SC O(1)外层扫+内存扫
- 方法二:TC O(N) SC O(N), 维护一个单调栈,空间换时间。
- 通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。
方法二代码
- 扫描数组,维护一个栈,这个栈的性质是:
- 当前元素比栈顶元素更小时,可以push进栈(栈顶到栈底只能递增),相当于存放下没有找到更大温度的温度们。
- 当前元素比栈顶元素更大时,说明找到了更大温度,就循环把小于当前元素的栈内元素依次全部弹出并计算距离,加入那个更大的当前元素。
- 为了方便,栈内只存元素的index

class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
res[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
return res;
}
}
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[T.length];
for (int i = 0; i < T.length; i++) {
if (stack.isEmpty()) {
stack.push(i);
} else if (T[i] > T[stack.peek()]) {
while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
res[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
} else {
stack.push(i);
}
}
return res;
}
}