跳到主要内容

单调栈

739. 每日温度

class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
stack<int> st;
vector<int> result(temperatures.size(), 0);
st.push(0);
for (int i = 1; i < temperatures.size(); i++) {
while (!st.empty() && temperatures[i] > temperatures[st.top()]) {
result[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return result;
}
};

496.下一个更大元素 I

class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int> st;
vector<int> res(nums2.size(), -1);
st.push(0);
for (int i = 1; i < nums2.size(); i++) {
while (!st.empty() && nums2[st.top()] < nums2[i]) {
res[st.top()] = nums2[i];
st.pop();
}
st.push(i);
}
unordered_map<int, int> mp;
for (int i = 0; i < nums2.size(); i++) {
mp.insert({nums2[i], i});
}
vector<int> ans(nums1.size());
for (int i = 0; i < nums1.size(); i++) {
ans[i] = res[mp[nums1[i]]];
}
return ans;
}
};

503.下一个更大元素 II

class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
for (int i = 0; i < n * 2; i++) {
while (!st.empty() && nums[st.top()] < nums[i % n]) {
res[st.top()] = nums[i % n];
st.pop();
}
st.push(i % n);
}
return res;
}
};

84. 柱状图中最大的矩形

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), 0);
heights.push_back(0);
stack<int> st;
st.push(0);
int ans = 0;
for (int i = 0; i < heights.size(); i++) {
while(heights[i] < heights[st.top()]) {
int mid = st.top();
st.pop();
int w = i - st.top() - 1;
int h = heights[mid];
ans = max(ans, w * h);
}
st.push(i);
}
return ans;
}
};