42. 接雨水
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
stack<int> st;
st.push(0);
int answer = 0;
for(int i = 1; i < n; i++)
{
while(!st.empty() && height[st.top()] < height[i])
{
int mid = height[st.top()];
st.pop();
if(!st.empty())
answer += (min(height[i], height[st.top()]) - mid) * (i - st.top() - 1);
}
st.push(i);
}
return answer;
}
};
84.柱状图中最大的矩形
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int answer = 0;
heights.insert(heights.begin(), 0); // 数组头部加入元素0
heights.push_back(0); // 数组尾部加入元素0
stack<int> st;
st.push(0);
for(int i = 0; i < heights.size(); i++)
{
while(!st.empty() && heights[i] < heights[st.top()])
{
int mid = st.top();
st.pop();
if(!st.empty())
answer = max(answer, heights[mid] * (i - st.top() - 1));
}
if(!st.empty() && heights[i] == heights[st.top()])
st.pop();
st.push(i);
}
return answer;
}
};