739. Daily Temperatures
mono increasing/decreasing stack
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[temperatures.length];
// monoincreasing stack
Stack<Integer> stack = new Stack<>();
for(int i=temperatures.length-1; i>=0; i--){
// use while not if!
while (!stack.isEmpty() && temperatures[stack.peek()]<=temperatures[i]){
stack.pop();
}
result[i] = stack.isEmpty() ? 0 : stack.peek() - i;
stack.push(i);
}
return result;
}
}
Previous297. Serialize and Deserialize Binary Tree!Next1541. Minimum Insertions to Balance a Parentheses String!
Last updated
Was this helpful?