// 暴力法
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. 每日温度
最新推荐文章于 2024-05-02 18:12:15 发布