1 Largest Rectangle in Histogram 原题目链接
分析:
题意:给定一个大小为n的非负整型数组,分别表示直方图的n个柱子高度,每个柱子宽度为1。返回该直方图所能形成的最大矩形面积。
思路:这道题跟LeetCode 11很相似,但是因为考虑柱子宽度,因此解题技巧不相同,此题考查单调栈的应用。我们首先在数组最后加入0,这是为了方便处理完数组中的所有高度数据。假设存储高度坐标的栈为stack,当前处理的高度坐标为i(i∈[0→n]):
① 如果当前stack为空,或者heights[i]大于等于栈顶坐标对应高度,则将i加入stack中;
② 如果heights[i]小于栈顶坐标对应高度,说明可以开始处理栈内的坐标形成的局部递增高度,以求得当前最大矩形面积。弹出当前栈顶坐标 = top,此时栈顶新坐标 = top',那么对应计算面积的宽度w = i - 1 - top'(若弹出栈顶坐标后,stack为空,则对应w = i),得到面积s = heights[top] * w,此时将i减一(因为进入循环i会加一,而待会儿需要重复考察第i个高度);
③ 遍历完成i∈[0→n],返回最大矩形面积。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
// Exceptional Case:
if(n == 0){
return 0;
}
if(n == 1){
return heights[0];
}
// insert 0 height
heights.push_back(0);
stack<int> st;
int ans = 0;
for(int i = 0; i <= n; i++){
if(st.empty() || heights[i] >= heights[st.top()]){
st.push(i);
}
else{
int top = st.top();
st.pop();
int w = st.empty()? i: i - 1 - st.top();
ans = max(ans, heights[top] * w);
i--;
}
}
return ans;
}
};
2 Maximal Rectangle (最大的矩形)
思路:
转换后矩阵可以变成下图所示矩阵,求最大矩阵相当于对每一行求直方图的最大矩形面积。
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix)
{
int result = 0;
if(matrix.empty() || matrix[0].empty())
return result;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int> > histogram(row , vector<int>(col,0));//直方图矩阵
for(int i = 0 ; i < row ; i++)
{
for(int j = 0 ; j < col ; j++)
{
if(i == 0) //第一行
histogram[i][j] = (matrix[i][j] == '1' ? 1 : 0);
else
histogram[i][j] = (matrix[i][j] == '1' ? histogram[i-1][j] + 1 : 0);//注意下一行不是等于上一行+当前行
}
}
//对每一行调用largestRectangleArea求最大矩形
for(int i = 0 ; i < row ; i++)
{
int tmp = largestRectangleArea(histogram[i]);
result = max(result , tmp);
}
return result;
}
int largestRectangleArea(vector<int> &height)
{
stack<int> stk;
height.push_back(0);
int maxArea = 0 ;
for(int i = 0 ; i < height.size() ;)
{
if(stk.empty() || height[i] > height[stk.top()])
{
stk.push(i);
i++;
}
else
{
int index = stk.top();
stk.pop();
int tmp = height[index] * (stk.empty() ? i : i-stk.top()-1);
maxArea = max(maxArea , tmp);
}
}
return maxArea;
}
};
参考:https://blog.csdn.net/huzhigenlaohu/article/details/52241462