leetcode:739. Daily Temperatures 单调栈

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;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值