1、单调栈
- 先进后出
- 单调性
- 记录\(t[i]\)之前会把所有\(≤t[i]\)的数据丢掉,不可能出现上面大下面小
从右向左遍历,单调递减栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> answer(n);
stack<int> s;
for (int i = n - 1; i >= 0; i--) {
int t = temperatures[i];
while ((!s.empty()) && (temperatures[s.top()] <= t)) { //弹出比该日气温低的(因为要找比该日气温高的(<=))
s.pop();
}
if (!s.empty()) { //栈非空,存在比该日气温高的日期
int nextIndex = s.top();
answer[i] = nextIndex - i;
}
s.push(i);
}
return answer;
}
};
从左向右遍历,单调递减栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> answer(n);
stack<int> s;
for (int i = 0; i < n; i++) {
int t = temperatures[i];
while ((!s.empty()) && (temperatures[s.top()] < t)) {//出栈的时候更新该出栈元素的答案
int j = s.top();
s.pop();
answer[j] = i - j;
}//当新元素比栈顶元素小时,新元素比栈中所有元素都小 -> 确保新元素小于栈中所有元素
s.push(i);
}
return answer;
}
};
从右向左遍历,单调递增栈
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
vector<int> result(n);
stack<int> s;
for (int i = n - 1; i >= 0; i--) {
int p = prices[i];
while (!s.empty() && prices[s.top()] > p) {
s.pop();
}
result[i] = s.empty() ? p : p - prices[s.top()];
s.emplace(i);
}
return result;
}
};
从左向右遍历,单调递增栈
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
int n = prices.size();
vector<int> result(prices.begin(), prices.end());
stack<int> s;
for (int i = 0; i < n; i++) {
int p = prices[i];
while (!s.empty() && p <= prices[s.top()]) {
int j = s.top();
result[j] = prices[j] - p;
s.pop();
} //确保了新元素大于栈中所有元素
s.emplace(i);
}
return result;
}
};