一、题目描述
请根据每日 气温 列表 temperatures ,重新生成一个列表,要求其对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
二、代码思路
- 暴力法:过于简单,直接看代码吧
- 单调栈模板问题,请看单调栈模板代码:
单调栈
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
//单调栈模板:
Stack<int[]> stk = new Stack();
int len = temperatures.length;
int res[] = new int[len];
for (int i = len - 1; i >= 0; i--) {
//从后往前遍历,栈的顶端一直留着相对位置i来说,其后最大且最近的元素
//从两方面理解逻辑:
//1. 对于temperatures[i]来说,它需要通过stk.peek()[0] < itself 来筛选出栈顶端需要是大于其自身的元素。
//2. 对于后续的其他元素来说,通过stk.peek()[0] < itself,能够保证当前是其后最大且最近的元素。
while (!stk.isEmpty() && stk.peek()[0] <= temperatures[i]) {
stk.pop();
}
if (stk.isEmpty()) {
res[i] = 0;
} else {
res[i] = stk.peek()[1] - i;
}
stk.push(new int[] {temperatures[i], i});
}
return res;
}
}
三、代码题解
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
//这题简单的一批
//嵌套一个for循环就得了
int res[] = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
int count = 0;
int flag = 0;
for (int j = i + 1; j < temperatures.length; j++) {
if (temperatures[i] < temperatures[j]) {
flag = 1;
count++;
break;
}
count++;
continue;
}
if (flag == 1) res[i] = count;
}
return res;
}
}