当前位置:网站首页>leetcode 739. Daily Temperatures 每日温度(中等)
leetcode 739. Daily Temperatures 每日温度(中等)
2022-08-11 01:37:00 【okokabcd】
一、题目大意
标签: 栈和队列
https://leetcode.cn/problems/daily-temperatures
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
二、解题思路
什么是单调栈?单调栈通过维持栈内值的单调递增(递减)性,在整体O(n)的时间内处理需要大小比较的问题。
思路:可以维持一个单调递减的栈,表示每天的温度,为了方便计算天数差,这里存放位置(即日期)而非温度本身。从左向右遍历温度数组,对于每个日期p,如果p的温度比栈顶存储位置q的温度高,则我们取出q,并记录q需要等待的天数p-q;重复这一过程,直到p的温度小于等于栈顶位置的温度或空栈时,我们将p插入栈顶,然后考虑下一天。在这个过程中栈内数组永远保持单调递减,避免了使用排序进行比较。最后若栈内剩余一些日期,则说明它们之后都没有出现更暖和的日期。
三、解题方法
3.1 Java实现
public class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] ans = new int[temperatures.length];
Stack<Integer> desStack = new Stack<>();
for (int i = 0; i < temperatures.length; i++) {
while (!desStack.isEmpty()) {
int preIndex = desStack.peek();
if (temperatures[i] <= temperatures[preIndex]) {
break;
}
desStack.pop();
ans[preIndex] = i - preIndex;
}
desStack.push(i);
}
return ans;
}
}
四、总结小记
- 2022/8/10 下雨、下雪本是很好玩的事,大了之后也不尽然,出行、生产、工作都会受到影响
边栏推荐
- dump_stack ()
- 【ASM】字节码操作 ClassWriter COMPUTE_FRAMES 的作用 与 visitMaxs 的关系
- 简陋的nuxt3学习笔记
- 15 DOM 扩展
- Engineering Design of Single-sided PCB Routing Impedance
- MySQL进阶查询
- what is an array
- 成功解决raise TypeError(‘Unexpected feature_names type‘)TypeError: Unexpected feature_names type
- 22/8/9 Collection of Greedy Problems
- Data Analysis Interview Manual "SQL"
猜你喜欢

单面PCB布线阻抗的工程设计

SQL语句--获取数据库表信息,表名、列名、描述注释等

数据分析面试手册《统计篇》
![[ASM] The relationship between the role of the bytecode operation ClassWriter COMPUTE_FRAMES and visitMaxs](/img/28/66370d46ebeb1e16b56ea2a36fe100.jpg)
[ASM] The relationship between the role of the bytecode operation ClassWriter COMPUTE_FRAMES and visitMaxs

【微波工程学习记录1】功率分配器和定向耦合器

Qt 中的隐式共享

21、阿里云oss

Linux安装redis数据库

【ASM】字节码操作 ClassWriter COMPUTE_FRAMES 的作用 与 visitMaxs 的关系

Please talk about for...in and for...of in JS (below)
随机推荐
13.cuBLAS开发指南中文版--cuBLAS中的Level-1函数copy()和dot()
还在用 Xshell?你 out 了,推荐一个更现代的终端连接工具,好用到爆!
The iterator and generator
Shengxin experiment record (part2)--tf.reduce_sum() usage introduction
paddle2.3和torch1.8在SentenceBert上的性能对比
Successfully resolved raise TypeError('Unexpected feature_names type')TypeError: Unexpected feature_names type
Vim take on a window.
数据库数据采集利器FlinkCDC
14.cuBLAS开发指南中文版--cuBLAS中的Level-1函数nrm2()和rot()
Update chromedriver driver programming skills │ selenium
报考PMP需要做些什么准备?
nvidia-smi:控制你的 GPU
最新国产电源厂家及具体型号pin-to-pin替代手册发布
zerorpc:async=True can be written as **{“async“: True}
分库分表ShardingSphere-JDBC笔记整理
OpenWrt之opkg详解
Deep Learning【第二章】
软件测试面试题:什么是Negative测试?
apache+PHP+MySQL+word press,安装word press时页面报错?
简陋的nuxt3学习笔记