zoukankan      html  css  js  c++  java
  • 74.Maximal Rectangle(数组中的最大矩阵)

    Level:

      Hard

    题目描述:

    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
    

    思路分析:

      我们的解题思路可以转换成求解Largest Rectangle in Histogram这道题的思路,假设有一个二维数组:

    1 1 0 1 0 1

    0 1 0 0 1 1

    1 1 1 1 0 1

    1 1 1 1 0 1

      首先初始height数组为1 1 0 1 0 1,它是二维数组第一行的复制,然后我们很容易得到最大的面积为2,然后我们升级数组,我们扫描第二行,当我们遇到matrix[1] [i]为0时,我们设置height[i]为0,否则设置height[i]=height[i]+1;这意味着height增加了1,因此height数组变成了0 2 0 0 1 2。此时最大的面积也为2。应用同样的方法直到扫描完整个数组,最后height数组为 2 4 2 2 0 4,因此最大的矩阵面积为2*4=8。

    代码:

    public class Solution{
        public int maximalRectangle(char [][]matrix){
            if(matrix==null||matrix.length==0)
                return 0;
            int []height=new int [matrix[0].length]; //构造高度数组
            for(int i=0;i<matrix[0].length;i++){
                if(matrix[0][i]=='1')
                    height[i]=1;
                else
                    height[i]=0;
            }
            int res=largestarea(height);
            for(int i=1;i<matrix.length;i++){
                resetheight(matrix,height,i); //更新高度数组
                res=Math.max(res,largestarea(height)); //更新最大的矩形面积
            }
            return res;
        }
        public void resetheight(char[][]matrix,int []height,int i){
            for(int j=0;j<matrix[0].length;j++){
                if(matrix[i][j]=='1')
                    height[j]=height[j]+1;
                else
                    height[j]=0;
            }
        }
        public int largestarea(int []height){
            if(height==null||height.length==0)
                return 0;
            Stack<Integer>s=new Stack<>();
            int  maxarea=0;
            for(int i=0;i<=height.length;i++){
                int h=(i==height.length)?0:height[i]; //最后添加一个零是为了能让栈中最后一个元素弹出
                if(s.isEmpty()||h>=height[s.peek()]){
                    s.push(i);
                }else{
                    int temp=s.pop();
                    maxarea=Math.max(maxarea,height[temp]*(s.isEmpty()?i:(i-s.peek()-1)));
                    i--; 
                }
            }
            return maxarea;
        }
    }
    
  • 相关阅读:
    很实用的html meta标签实现页面跳转
    oracle 实例名和服务名以及数据库名区别
    Oracle 创建 DBLink 的方法
    Java (六):java中Math常用方法
    Java (四):String,StringBuilder,StringBuffer三者的区别
    ROS Learning-001 安装 ROS indigo
    Windows cmd 将命令(/指令)写到一个文件里,直接运行这个文件。提高工作效率
    Blender 基础 骨架-02 骨架的各种呈现方式
    Blender 基础 骨架 01
    Python 解决 :NameError: name 'reload' is not defined 问题
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11098555.html
Copyright © 2011-2022 走看看