【LeetCode 85】最大矩形(第二遍)

题目链接

【题解】

首先 我们处理出来一个数组 a[i][j]. 这个数组的含义是,矩阵中(i,j)包括自身往上有多少个连续的1. 然后我们枚举行i. 表示我们现在要考察的矩阵的下边在第i行。 然后我们再处理出来一个一维数组heights[j] 其中heights[j] = a[i][j] 然后,问题就转化为在一个柱状图里面求一个最大的矩形了。用这个方法 做就行了。 枚举行O(N)的复杂度,柱状图求最大的矩阵也是O(N)的复杂度 因此这道题的时间复杂度为O(N^2)

【代码】

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size();
        int m = 0;
        if (!matrix.empty()) m = matrix[0].size();
        int a[500+10][500+10];
        for (int i = 0;i< n;i++){
            for (int j = 0;j < m;j++){
                if (i-1>=0 && matrix[i-1][j]=='1' && matrix[i][j]=='1'){
                    a[i][j] = a[i-1][j]+1;
                }else a[i][j] = matrix[i][j]-'0';
                //cout<<a[i][j]<<" ";
            }   
            //cout<<endl;
        }
        
        int top = 0,sta[500+10];
        int heights[500+10];
        int ma = 0;
        for (int i = 0;i < n;i++){
            for (int j = 0;j<m;j++){
                heights[j+1] = a[i][j];
            }
            top = 0;
            heights[0] = 0;
            for (int j = 1;j <= m;j++){
                if (top==0 || heights[sta[top]]<=heights[j]){
                    sta[++top] = j;
                }else{
                    while (top>0 && heights[sta[top]]>heights[j]){
                        ma = max(ma,(j-1-sta[top-1])*heights[sta[top]]);
                        top--;
                    }
                    sta[++top] = j;
                }
            }
            while (top>0){
                ma = max(ma,(m-sta[top-1])*heights[sta[top]]);
                top--;
            }
        }
        return ma;
    }
};
posted @ 2020-02-11 07:24  AWCXV  阅读(151)  评论(0编辑  收藏  举报