class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int[] ans = new int[T.length];
for(int i = 0; i < T.length; i++) {
while(!stack.isEmpty() && T[i] > T[stack.peek()]) {
int index = stack.pop();
ans[index] = i - index;
}
stack.push(i);
}
return ans;
}
}
思路二:for循环从后往前遍历,元素倒序入栈,正序出栈
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int[] ans = new int[T.length];
for (int i = T.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && T[stack.peek()] <= T[i]) {
stack.pop();
}
ans[i] = stack.isEmpty() ? 0 : (stack.peek() - i);
stack.push(i);
}
return ans;
}
}
leetcode-739-每日温度
最新推荐文章于 2024-08-23 01:05:03 发布