LeetCode——maximal-rectangle

Question

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

Solution

这个题目可以借鉴LeetCode——largest-rectangle-in-histogram 的思路,求最大矩阵的面积,所以我们只需要按行把给定’0’,‘1’矩阵,转换成对应的高度即可,然后计算最大矩阵面积。

Code

时间复杂度O(n^2).

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        int row = matrix.size();
        if (row <= 0)
            return 0;
        int col = matrix[0].size();
        vector<vector<int>> heights;
        for (int i = 0; i < row; i++) {
            vector<int> tmp;
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] != '0') {
                    // 累加高度
                    if (i - 1 >= 0 && matrix[i - 1][j] != '0')
                        matrix[i][j] += (matrix[i - 1][j] - '0');
                    tmp.push_back(matrix[i][j] - '0');
                } else {
                    // 被‘0’断开了,就需要计算一次
                    if (tmp.size() > 0) {
                        heights.push_back(tmp);
                        tmp.clear();
                    }
                }
            }
            if (tmp.size() > 0)
                heights.push_back(tmp);
        }
        int res = 0;
        for (int i = 0; i < heights.size(); i++) {
            res = max(res, calc(heights[i]));
        }
        return res;
    }
    // 给定高度,求最大矩阵面积,时间复杂度O(n)
    int calc(vector<int>& height) {
        if (height.size() <= 0)
            return 0;
        stack<int> tb;
        int n = height.size();
        int res = 0;
        for (int i = 0; i < n; i++) {
            while (!tb.empty() && height[tb.top()] >= height[i]) {
                int index = tb.top();
                tb.pop();
                if (tb.empty()) {
                    res = max(res, i * height[index]);
                } else {
                    res = max(res, (i - tb.top() - 1) * height[index]);
                }
            }
            tb.push(i);
        }
        while (!tb.empty()) {
            int index = tb.top();
            tb.pop();
            if (tb.empty()) {
                res = max(res, n * height[index]);
            } else {
                res = max(res, (n - tb.top() - 1) * height[index]);
            }
        }
        return res;
    }
};

转载于:https://www.cnblogs.com/zhonghuasong/p/7760766.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值