Leetcode 739. 每日温度 单调栈

地址 https://leetcode-cn.com/problems/daily-temperatures/

请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度。
如果气温在这之后都不会升高,请在该位置用 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 <= 10^5
30 <= temperatures[i] <= 100

解答
在Leetcode 84 柱状图中最大的矩形 已经解释过了单调栈。
单调栈非常适合解答连续空间中,比当前元素大或者小的最近元素。
时间复杂度O(N)

class Solution {
public:
	vector<int> dailyTemperatures(vector<int>& t) {
		vector<int> ans(t.size());
		stack<int> st;

		for (int i = t.size()-1; i>=0; i--) {
			while (!st.empty() && t[i] >= t[st.top()]) { st.pop(); }
			if (st.empty()) ans[i] = 0;
			else { ans[i] = st.top()-i; }
			st.push(i);
		}

		return ans;
	}
};

我的视频题解空间

posted on   itdef  阅读(79)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2021-01-29 LeetCode 102. 二叉树的层序遍历 && 剑指 Offer 32 - II. 从上到下打印二叉树 II
2021-01-29 LeetCode 剑指 Offer 32 - I.. 从上到下打印二叉树

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示