leetcode/src/s0739_daily_temperatures.cpp

34 lines
891 B
C++

#include "s0739_daily_temperatures.hpp"
vector<int> S0739::dailyTemperatures(vector<int>& temperatures) {
int len = temperatures.size();
if (len == 0) {
return vector<int> {};
} else if (len == 1) {
return vector<int> {0};
}
// 栈中的元素为向量的下标
// 向量下标对应的元素从栈底到栈顶单调递增
stack<int> s;
// 初始化 ans 中的所有元素为 0
vector<int> ans(len, 0);
for (int i{0}; i < len; ++i) {
// 当栈为空时,直接入栈然后 continue
if (s.empty()) {
s.push(i);
continue;
}
// 当我们发现当前元素比栈顶元素大时,循环弹出
// 注意,是循环弹出,而不是 if 弹出
while (temperatures[i] > temperatures[s.top()]) {
ans[s.top()] = i - s.top();
s.pop();
if (s.empty()) {
break;
}
}
s.push(i);
}
return ans;
}