题目描述:
解法一(暴力):
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
int n = T.size();
vector<int> res(n, 0);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (T[j] > T[i]) {
res[i] = j - i;
break;
}
}
}
return res;
}
};
解法二(跳跃):
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
int n = T.size();
vector<int> res(n, 0);
for (int i = n - 2; i >= 0; i--) {
for (int j = i + 1; j<n; j += res[j]) {
if (T[i] < T[j]) {
res[i] = j - i;
break;
}
else if (res[j] == 0) {
res[i] = 0;
break;
}
}
}
return res;
}
};
解法三(单调栈):
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> stk;
vector<int> res;
for (int i = T.size() - 1; i >= 0; i--) {
while (!stk.empty() && T[i] >= T[stk.top()]) {
stk.pop();
}
if (stk.empty()) res.push_back(0);
else res.push_back(stk.top() - i);
stk.push(i);
}
reverse(res.begin(), res.end());
return res;
}
};