根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。
Review:
利用栈思想解题,把气温对应索引存入栈中,每遍历一个温度就与之前温度比较,若大于之前温度,则计算天数
此栈为递减栈
Code:
也可以使用数组实现栈,速度会快一些,但我就不浪费这个时间了
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> helper = new Stack<>();
int[] res = new int[T.length];
for (int i = 0; i < T.length; i++) {
while (!helper.empty()&&T[helper.peek()]<T[i]){
int temp = helper.pop();
res[temp] = i-temp;
}
helper.push(i);
}
return res;
}
}
本文介绍了一种基于栈的数据结构解决气温预测问题的算法。通过遍历气温列表,算法能高效地计算出每个日期之后气温上升所需的天数。适用于天气预报等场景。
314

被折叠的 条评论
为什么被折叠?



