1060. 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].
Example
Example 1:
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Explanation:
Just find the first day after it which has higher temperatures than it.
Example 2:
Input: temperatures = [50, 40, 39, 30]
Output: [0,0,0,0]
Notice
1.The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]
解法1:单调栈。
因为是对每个节点求右边第一个比其大的元素,所以用单调递减栈。
class Solution {
public:
/**
* @param temperatures: a list of daily temperatures
* @return: a list of how many days you would have to wait until a warmer temperature
*/
vector<int> dailyTemperatures(vector<int> &temperatures) {
int n = temperatures.size();
vector<int> result(n, 0);
stack<int> s;
for (int i = 0; i < n; ++i) {
while(!s.empty() && temperatures[s.top()] < temperatures[i]) {
result[s.top()] = i - s.top();
s.pop();
}
s.push(i);
}
while(!s.empty()) {
result[s.top()] = 0;
s.pop();
}
return result;
}
};
二刷:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
stack<int> stk;
vector<int> res(n, 0);
for (int i = 0; i < n; i++) {
while (!stk.empty() && temperatures[stk.top()] < temperatures[i]) {
res[stk.top()] = i - stk.top();
stk.pop();
}
stk.push(i);
}
return res;
}
};
也可以反过来(n-1 .. 0)入栈。此时从栈底到栈顶仍然是递减,但如果按index顺序来则是递增。
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> res(n);
stack<int> stk;
for (int i = n - 1; i >= 0; i--) {
while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) {
stk.pop();
}
res[i] = stk.empty() ? 0 : (stk.top() - i);
stk.push(i);
}
return res;
}
本文介绍了一种使用单调栈数据结构解决气温预测问题的方法。通过遍历每日温度列表,算法能高效地找出每一天之后首次出现的更暖温度,并返回等待天数列表。示例包括具体输入输出及代码实现。
5万+

被折叠的 条评论
为什么被折叠?



