zoukankan      html  css  js  c++  java
  • 85. Maximal Rectangle

    Problem:

    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
    

    思路
    遍历二维数组中的每一个元素,如果这个元素非0,则储存其对应的左边界和右边界,乘上对应的高度,然后求max即得到最大值。

    Solution (C++):

    int maximalRectangle(vector<vector<char>>& matrix) {
        if (matrix.empty() || matrix[0].empty())  return 0;
        int m = matrix.size(), n = matrix[0].size();
        vector<int> left_bound(n), right_bound(n, n-1), height(n);
        int max_area = 0;
        
        for (int i = 0; i < m; ++i) {
            int cur_left = 0, cur_right = n-1;
            for (int j = 0; j < n; ++j) {
                if (matrix[i][j] == '1')  height[j]++;
                else  height[j] = 0;
            }
            
            for (int j = 0; j < n; ++j) {
                if (matrix[i][j] == '1')  left_bound[j] = max(left_bound[j], cur_left);
                else  {left_bound[j] = 0; cur_left = j+1;}
            }
            for (int j = n-1; j >= 0; --j) {
                if (matrix[i][j] == '1')  right_bound[j] = min(right_bound[j], cur_right);
                else  {right_bound[j] = n-1; cur_right = j-1;}
            }
            for (int j = 0; j < n; ++j) {
                max_area = max(max_area, (right_bound[j]-left_bound[j]+1) * height[j]);
            }
        }
        return max_area;
    }
    

    性能

    Runtime: 16 ms  Memory Usage: 10.5 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    axios 进行类库封装
    vue的中vuex为何需要mutation更新状态,vue-router的路由的理解
    发布订阅者模式、观察者模式总结
    es 模块的基础知识,深度了解
    绑定事件的模型
    rem+media+jquery布局结局方案
    VDOM总结
    react-redux
    发布网站配置文件和SSL
    css3d旋转
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12290089.html
Copyright © 2011-2022 走看看