zoukankan      html  css  js  c++  java
  • 【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;
        }
    };
    
  • 相关阅读:
    python入学代码
    python安装和pycharm安装与笔记
    python预习day1
    python-tyoira基本
    Typora基础
    学习一下saltstack 服务器批量管理
    消息队列与kafka
    消息队列rabbitmq
    redis数据库在linux上的学习
    蓝绿部署、滚动发布、灰度发布的介绍以及最佳实践
  • 原文地址:https://www.cnblogs.com/AWCXV/p/12293730.html
Copyright © 2011-2022 走看看