当前位置:网站首页>剑指 Offer II 038. 每日温度
剑指 Offer II 038. 每日温度
2022-07-04 05:46:00 【小白码上飞】
概要
使用栈,遍历数组,比较当前数字是否比栈顶元素大。大则出栈处理,直到栈空或者当前数字小于栈顶数字时,将当前数字入栈。
题目
请根据每日 气温 列表 temperatures ,重新生成一个列表,要求其对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
链接:https://leetcode.cn/problems/iIQa4I
思路
其实和行星碰撞的很像。
我们用一个栈来保存数组中每个元素的下标,从做开始遍历数组。
- 如果栈为空,则入栈。
- 如果栈不为空,比较栈顶和当前元素的大小
- 如果当前元素大,则用当前元素下标和栈顶下标相减,得到栈顶元素“需要等待的天数”。之后再继续和栈里的元素比较大小。
- 如果当前元素小,则入栈。
这样始终让栈顶的元素是最小的,一旦有更大值出现,就把栈中比他小的值都处理掉。
解法:单调栈
代码
public int[] dailyTemperatures2(int[] temperatures) {
int[] result = new int[temperatures.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < temperatures.length; i++) {
if (stack.isEmpty()) {
stack.push(i);
continue;
}
int current = temperatures[i];
while (!stack.isEmpty() && current > temperatures[stack.peek()]) {
int index = stack.pop();
result[index] = i - index;
}
stack.push(i);
}
// 处理观测不到高温的日子
while (!stack.isEmpty()) {
result[stack.pop()] = 0;
}
return result;
}
执行结果
这里注意,直接使用了Deque来代替Stack,因为Stack的效率实在太低了……
边栏推荐
- Weekly summary (*63): about positive energy
- 724. Find the central subscript of the array
- How to solve the component conflicts caused by scrollbars in GridView
- 十二. golang其他
- 光模块字母含义及参数简称大全
- Excel comparator
- AWT介绍
- [high concurrency, high performance and high availability of massive data MySQL practice-7] - memory data drop disk
- Etcd database source code analysis - initialization overview
- fastjson
猜你喜欢
Upper computer software development - log information is stored in the database based on log4net
How to configure static IP for Kali virtual machine
Online shrimp music will be closed in January next year. Netizens call No
ANSYS command
js arguments参数使用和详解
[MySQL practice of massive data with high concurrency, high performance and high availability -8] - transaction isolation mechanism of InnoDB
Steady! Huawei micro certification Huawei cloud computing service practice is stable!
2022 a special equipment related management (elevator) examination questions simulation examination platform operation
Letter meaning and parameter abbreviation of optical module Daquan
2022 R2 mobile pressure vessel filling retraining question bank and answers
随机推荐
Arc135 C (the proof is not very clear)
冲击继电器JC-7/11/DC110V
JS string splicing enhancement
LC weekly 300
Ping port artifact psping
Flask
How to use postman to realize simple interface Association [add, delete, modify and query]
Impact relay jc-7/11/dc110v
Excel comparator
js获取对象中嵌套的属性值
VB. Net calls ffmpeg to simply process video (class Library-6)
HMS v1.0 appointment. PHP editid parameter SQL injection vulnerability (cve-2022-25491)
[excel] PivotChart
input显示当前选择的图片
C language simple student management system (including source code)
每周小结(*63):关于正能量
Supplement the JS of a video website to decrypt the video
复合非线性反馈控制(二)
Introduction to AMBA
VB.net 调用FFmpeg简单处理视频(类库——6)