输入:一个整数数组 temperatures,表示每天的温度。
要求:
-
遍历
temperatures数组。 -
对于数组中的每一天(
i),你需要找到在未来(j > i)需要等待多少天,才能遇到一个更高的温度。
输出:一个与 temperatures 等长的答案数组 answer。
-
answer[i]等于你需要等待的天数 (j - i)。 -
如果未来再也没有更高的温度出现,则
answer[i]设为0。
思路:很标准的单调栈题,没什么好讲的,只需要注意要进出栈的是序号而不是值即可。
复杂度:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n, 0);
stack<int> s;
for (int i = 0; i < n; ++i) {
while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
int prev_index = s.top();
s.pop();
ans[prev_index] = i - prev_index;
}
s.push(i);
}
return ans;
}
};
1631

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



