LCR 038. Daily temperature
Problem-solving ideas
- monotonic stack
- Find each element with an index greater than its first element
- If not write 0 directly
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;
}
}