每日一题(2020-06-11)739. 每日温度

[739. 每日温度]

难度 中等

根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures

解法:单调栈

可以使用单调栈 stack 来解决这个问题,栈内存储的是对应温度在数组中下标,。

对于 temperatures 中的第 i 个元素

  • 如果 temperatures [i] <= 栈顶元素(即当前温度 <= 栈顶元素所表示的温度),直接将 i 入栈
  • 如果 temperatures [i] > 栈顶元素(即当前温度 > 栈顶元素所表示的温度)

​ 栈顶元素出栈(记作 index),则 ans[index] = i - index,重复该操作直到栈为空 或者 temperatures [i] <= 栈顶元素

class Solution {
    public int[] dailyTemperatures(int[] T) {
    	int len = T.length;
    	int[] ans = new int[len];
    	if(T == null || T.length == 0) {
    		return ans;
    	}
    	Stack<Integer> stack = new Stack();
    	stack.push(0);
    	for(int i = 1; i < len; i++) {
			while(!stack.isEmpty() && T[i] > T[stack.peek()]) {				
				ans[stack.peek()] = i - stack.peek();
				stack.pop();
			}
			stack.push(i);
    	}
    	//对
    	//因为数组的元素默认为 0 ,这段代码可以省略
    	while(!stack.isEmpty()) {
			ans[stack.peek()] = 0;
			stack.pop();   	
    	}
		return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

两只Tigers跑得快

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值