Daily Temperatures
2024-09-07 19:57:49
Given a list of daily temperatures T
, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0
instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73]
, your output should be [1, 1, 4, 2, 1, 1, 0, 0]
.
Note: The length of temperatures
will be in the range [1, 30000]
. Each temperature will be an integer in the range [30, 100]
.
分析:
为了找到后面过了几天会有比当前值更大的值,所以,我们需要从尾遍历,我们用一个stack来存当前最大值。
public class Solution {
public int[] dailyTemperatures(int[] T) {
if (T == null) return null;
int[] result = new int[T.length];
Stack<Temperature> stack = new Stack<>(); for (int i = T.length - ; i >= ; i--) {
if (stack.isEmpty()) {
result[i] = ;
stack.push(new Temperature(T[i], i));
} else if (stack.peek().value > T[i]) {
result[i] = stack.peek().index - i;
stack.push(new Temperature(T[i], i));
} else {
while (!stack.isEmpty() && stack.peek().value <= T[i]) {
stack.pop();
}
if (stack.isEmpty()) {
result[i] = ;
} else {
result[i] = stack.peek().index - i;
}
stack.push(new Temperature(T[i], i));
}
}
return result;
}
} class Temperature {
int value;
int index; public Temperature(int value, int index) {
this.value = value;
this.index = index;
}
}
最新文章
- UWP学习记录10-设计和UI之控件和模式7
- iOS开发阶段技能总结
- 使用bokeh-scala进行数据可视化
- Android 正则表达式
- Spring中配置数据源的4种形式(转)
- 去除VS2010中中文注释下的红色波浪线
- [QT]QT概述
- SSM框架—详细整合教程(Spring+SpringMVC+MyBatis)
- JavaScript树(二) 二叉树搜索
- 解决Popup StayOpen=true时,永远置顶的问题
- 【一天一道LeetCode】#44. Wildcard Matching
- 设置radio选中
- 给django视图类添加装饰器
- Kernel数据结构移植(list和rbtree)
- 通用模块设计UMD
- YSLOW(一款实用的网站性能检测工具)
- nginx配置http访问自动跳转到https
- linux 模拟发http请求的例子
- 158A
- oracle之回滚数据表 笔记