题目
暴力
暴力有两种:
- 一种是每次遍历当前位置后续的元素,寻找更大值,由于数组长度最大为 1e5 ,因此会超时;
- 第二种是建立一个元素索引,每次遍历当前元素温度 +1 到 100 度的元素,若能找到,则为目标,若找不到,说明结果为 0 。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n), next(101, INT_MAX);
for(int i = n - 1; i >= 0; --i) {
int index = INT_MAX;
for(int j = temperatures[i] + 1; j <= 100; ++j)
index = min(index, next[j]);
if(index != INT_MAX)
ans[i] = index - i;
next[temperatures[i]] = i;
}
return ans;
}
};
单调栈
维护一个栈,将数组元素按顺序入栈,每个元素入栈的时候判断一下该元素是否比之前某些元素大,如果是,则更新栈内相关元素,如果不是,则入栈。
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n);
stack<int> s;
for (int i = 0; i < n; ++i) {
while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
int previousIndex = s.top();
ans[previousIndex] = i - previousIndex;
s.pop();
}
s.push(i);
}
return ans;
}
};