1.接雨水
1.1 题目
https://leetcode.cn/problems/trapping-rain-water/description/
1.2 题解
class Solution {
public:
int trap(vector<int>& height)
{
int count = 0;
stack<int> st;
st.push(0);
for (int i = 1; i < height.size(); i++)
{
while (!st.empty() && height[i] > height[st.top()])
{
int rightHeight = height[i];
int middleHeight = height[st.top()];
st.pop();
if (!st.empty())
{
int leftHeight = height[st.top()];
//计算长
int h = min(leftHeight, rightHeight) - middleHeight;
//计算宽
int w = i - st.top() - 1;
//计算雨水面积
int s = w * h;
count += s;
}
}
st.push(i);
}
return count;
}
};
2.柱状图中最大的矩形
2.1 题目
https://leetcode.cn/problems/largest-rectangle-in-histogram/description/
2.2 题解
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
stack<int> st;
st.push(0);
int result = 0;
//前后添加0
vector<int> tmp;
tmp.push_back(0);
for (const auto& i : heights)
{
tmp.push_back(i);
}
tmp.push_back(0);
for (int i = 1; i < tmp.size(); i++)
{
while (!st.empty() && tmp[i] < tmp[st.top()])
{
//右边比他小的
int h = tmp[st.top()];
st.pop();
if (!st.empty())
{
int index = st.top();
int w = i - index - 1;
int s = w * h;
result = max(result, s);
}
}
st.push(i);
}
return result;
}
};