LeetCode_Maximal Rectangle

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

分析: 对于每一列从右到左看成一个直方图,每个直方图计算最大面积的时间复杂度为O(n) 所以总的时间复杂度是O(n2

class Solution {

public:

    int maxArea(vector<int> &m)

    {

        int size = m.size();

        stack<int> s;

        int area, maxArea = 0;

        for(int i = 0; i< size; ++i)

        {

            if(s.empty() || m[i] >= m[s.top()] )

            {

                s.push(i);

                continue;

            }            

            int tp = s.top();

            s.pop();

            area = m[tp] * (s.empty() ? i : i -s.top() -1);

            maxArea = maxArea > area ? maxArea : area;

            --i;

        }

        

        while(!s.empty()){

            int    tp = s.top();

            s.pop();

            area = m[tp] * (s.empty() ? size: size - s.top() -1);

            maxArea = maxArea > area ? maxArea : area;

        }

        return maxArea;

    }

    int maximalRectangle(vector<vector<char> > &matrix) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        int row = matrix.size();

        if(row < 1) return 0;

        int column = matrix[0].size();

        if(column <1) return 0;

        

        int area , res = 0;

        

        vector<int> m(row,0);

        for(int i = 0; i< column; ++i)

        {

            for(int j = 0; j< row; ++j)

               if(matrix[j][i] == '0')

                        m[j] = 0;

                else

                        m[j]++;

        

            area = maxArea(m);

            res = res > area ? res : area;

        }

        return res;

    }

};

 

你可能感兴趣的:(LeetCode)