Ideas:
Observe the example given:
Given a list temperatures = [73, 74, 75, 71, 69, 72, 76, 73] , the output should be [1, 1, 4, 2, 1, 1, 0, 0]
Traverse from the front to the back, if the temperature is greater than the previous one, pop the previous one, save the current subscript-the value of the previous value subscript, and finally save the current subscript into the stack. Obviously, the monotonic stack is used
class Solution {
public int[] dailyTemperatures(int[] T) {
int n=T.length;
Deque<Integer> stack=new ArrayDeque<>();
int[] ans=new int[n];
for(int i=0;i<n;i++){
//注意:存入stack的是下标
while(!stack.isEmpty()&&T[i]>T[stack.peekLast()]){
int j=stack.removeLast();
ans[j]=i-j;
}
//要在把所有<temp的温度弹出后才能把temp压入栈中
//还包含了一层意思,如果不满足while的条件,也就是
//temp<stack.peek()也压入栈中
stack.addLast(i);
}
return ans;
}
}