// 暴力法
class Solution {
public int[] dailyTemperatures(int[] T) {
int len = T.length;
int[] result = new int[len];
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (T[i] < T[j]) {
result[i] = j - i;
break;
}
}
}
return result;
}
}
// 暴力法优化
// 先从计算右边,那么我们计算过的位置就不需要重复计算
class Solution {
public int[] dailyTemperatures(int[] T) {
int len = T.length;
int[] result = new int[len];
//从右向左遍历
for (int i = len - 2; i >= 0; i--) {
// j+= result[j]是利用已经有的结果进行跳跃
for (int j = i + 1; j < len; j += result[j]) {
if (T[j] > T[i]) {
result[i] = j - i;
break;
}
//遇到0表示后面不会有更大的值,那当然当前值就应该也为0
else if (result[j] == 0) {
result[i] = 0;
break;
}
}
}
return result;
}
}
// 栈
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int len = T.length;
int[] result = new int[len];
for (int i = 0; i < len; i++) {
while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
result[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
return result;
}
}
leetcode739. 每日温度
最新推荐文章于 2025-05-28 15:34:01 发布
本文介绍了一种用于预测未来气温变化的算法优化方案。通过三种不同的方法:暴力法、暴力法优化及栈的应用,实现了对气温数据的有效处理。优化后的算法能够显著减少计算时间和资源消耗,提高预测效率。
822

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



