LCR 038. 每日温度
解题思路
- 单调栈
- 查找每一个元素的比他的第一个元素的索引
- 如果没有 直接写0
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
// 单调栈
int n = temperatures.length;
int[] res = new int[n];
Stack<Integer> s = new Stack<>();// 存放元素的索引
for(int i = n - 1; i >= 0; i--){
while(!s.isEmpty() && temperatures[s.peek()] <= temperatures[i]){
s.pop();
}
// 针对当前元素
res[i] = s.isEmpty() ? 0 : (s.peek() - i);
s.push(i);
}
return res;
}
}