题干
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,
给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],
你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
想法
今天的题干排版有点丑陋。
回到题上,题意就是需要找到数组里每一个数往后最近的那个比他大的数。
于是想到单调栈
用一个stack,栈顶维护当前最高的温度。
也就是说:
可以维护一个存储下标的单调栈,从栈底到栈顶的下标对应的温度列表中的温度依次递减。如果一个下标在单调栈里,则表示尚未找到下一次温度更高的下标。
遍历数组,比他大的,更新,结果就是现在的下标减去之前最大的
比他小的就光push进stack
java代码
package daily;
import java.util.*;
public class DailyTemperatures {
public int[] dailyTemperatures(int[] T) {
int len = T.length;
int[] res = new int[len];
//stack维护还没找到比他大的
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < len; i++) {
int temperature = T[i];
while (!stack.isEmpty() && temperature > T[stack.peek()]) {
int preindex = stack.pop();
res[preindex] = i - preindex;
}
stack.push(i);
}
return res;
}
public static void main(String[] args) {
DailyTemperatures dailyTemperatures = new DailyTemperatures();
int[] T = {73, 74, 75, 71, 69, 72, 76, 73};
int[] res = dailyTemperatures.dailyTemperatures(T);
System.out.println(Arrays.toString(res));
}
}