难度:Hard
原题连接
内容描述
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
思路1 - 时间复杂度: O(n^3)- 空间复杂度: O(1)******
第一种暴力的方法去解,先求出每一个数向右有多少个“1”,记录下长度count1,在这个数的位置向下寻找,若下面的长度小于count1,则count1取较小的值。若为0就计算矩阵的大小,直到遍历所有的数。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int len1 = matrix.size();
if(!len1)
return 0;
int len2 = matrix[0].size();
int ans = 0;
for(int t = 0;t < len1;++t)
for(int i = 0;i < len2;++i)
{
int count1 = 0;
while(i + count1 < len2 && matrix[t][i + count1] - '0')
++count1;
if(count1)
{
int row = 1;
ans = max(ans,row * count1);
for(int j = t + 1;j < len1;++j)
{
int count2 = 0;
while(count2 <= count1 && matrix[j][i + count2] - '0')
++count2;
if(!count2)
break;
if(count1 > count2)
count1 = count2;
++row;
ans = max(ans,row * count1);
}
}
}
return ans;
}
};
思路2 - 时间复杂度: O(n^2)- 空间复杂度: O(n)******
对上述算法进行优化,计算每个数的高度和这个高度向左的位置和向右的位置,这样只要在O(n^2)的时间复杂内就能完成
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int len1 = matrix.size();
if(!len1)
return 0;
int len2 = matrix[0].size();
int height[len2],l[len2],r[len2];
memset(height,0,sizeof(height));
memset(l,0,sizeof(l));
for(int i = 0;i < len2;++i)
r[i] = len2;
int ans = 0;
for(int i = 0;i < len1;++i)
{
int t_l = 0,t_r = len2;
for(int j = 0;j < len2;++j)
if(matrix[i][j]-'0')
height[j] = height[j] + 1;
else
height[j] = 0;
for(int j = 0;j < len2;++j)
if(matrix[i][j]-'0')
l[j] = max(l[j],t_l);
else
{
t_l = j + 1;
l[j] = 0;
}
for(int j = len2 - 1;j >= 0;--j)
if(matrix[i][j]-'0')
r[j] = min(r[j],t_r);
else
{
t_r = j;
r[j] = len2;
}
for(int j = 0;j < len2;++j)
ans = max(ans,(r[j] - l[j]) * height[j]);
}
return ans;
}
};