leetcode:739. Daily Temperatures 单调栈
来源:互联网 发布:多少岁淘宝能贷款 编辑:程序博客网 时间:2024/05/17 05:02
Given a list of daily temperatures
, produce a list 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 temperatures = [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]
.
题意:输入一个数组,代表每天的温度,求解每天需要经过几天会升温,即需找数组每个元素右边第一个比自己大的数。利用单调栈性质创建单调递减栈,遍历数组入栈,当将要入栈元素小于栈顶元素时入栈,若要入栈元素大于栈顶元素时,表示入栈元素为所求元素,记录索引,弹出栈顶元素,将此元素压栈,重新比较,一次循环时间复杂度O(n)。
样例解析:
73入栈,74>73,73出栈,74入栈,74使得73出栈,所以73需要等待1-0=1天 ,栈内元素74.
75入栈,75>74, 74出栈,75入栈,75使得74出栈,所以74需要等待2-1=1天,栈内元素75.
71入栈,71<75,直接入栈,栈内元素 75,71
69直接入栈,栈内元素75,71,69
72入栈,72>69,69出栈,72使69出栈,所以69需要等待5-4=1天,此时栈内元素75,71,由与72>71,任不满足单调栈性质,71出栈,72使71出栈,所以71需要等待5-3=2天,站内元素75,75>72,72直接入栈,栈内元素为:75,72.
以此类推。。。
代码如下:
class Solution { public int[] dailyTemperatures(int[] temperatures) { Stack<Integer> s = new Stack<Integer>(); int[] res = new int[temperatures.length]; for(int i=0;i<temperatures.length;i++){ if(s.isEmpty()||temperatures[i]<temperatures[s.peek()]){ s.push(i); } else { while(!s.isEmpty()&&temperatures[s.peek()]<temperatures[i]){ int index = s.pop(); res[index] = i-index; } s.push(i); } } return res; }}
- leetcode:739. Daily Temperatures 单调栈
- [leetcode] 739. Daily Temperatures
- Leetcode 739. Daily Temperatures
- LeetCode刷题 | 739. Daily Temperatures
- leetcode weekly contest 61(739. Daily Temperatures)
- LeetCode.739 Daily Temperatures
- 739. Daily Temperatures
- 739. Daily Temperatures
- 739. Daily Temperatures
- LWC 61:739. Daily Temperatures
- Daily Temperatures问题及解法
- LeetCode-[单调栈]Largest Rectangle in Histogram
- Daily
- 单调栈 单调队列
- 【单调队列】leetcode MinStack
- LeetCode Largest Rectangle in Histogram (单调栈)
- LeetCode 84 Largest Rectangle in Histogram (单调栈)
- LeetCode 85 Maximal Rectangle (最大子矩形 单调栈)
- 精通Excel数据统计与分析
- 解决AndroidStudio导入项目在 Building gradle project info 一直卡住
- 字符游戏-智能蛇
- 哈夫曼树的生成及哈夫曼编码
- 第15周项目4
- leetcode:739. Daily Temperatures 单调栈
- IT行业风险投资
- MySQL存储引擎--MyISAM与InnoDB区别
- 推荐系统之用户行为分析
- 单点登录的三种实现方式
- 史上最详细Cox回归列线图制作教程
- 初识java这个小姑娘(一)
- celery17.1-17.3
- vim 替换命令