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 2022-01-29 20:23  itdef  阅读(60)  评论(0编辑  收藏  举报

导航