每日温度
题目链接:每日温度
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
方法一:栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n,0);
stack<pair<int,int>> s;
for (int i = 0;i < n;i++) {
while (!s.empty() && s.top().first < temperatures[i]) {
ans[s.top().second] = i - s.top().second;
s.pop();
}
s.push({temperatures[i],i});
}
while (s.size()) {
ans[s.top().second] = 0;
s.pop();
}
return ans;
}
};