zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 85 最大矩形

    85. 最大矩形

    给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

    示例:

    输入:
    [
    [“1”,“0”,“1”,“0”,“0”],
    [“1”,“0”,“1”,“1”,“1”],
    [“1”,“1”,“1”,“1”,“1”],
    [“1”,“0”,“0”,“1”,“0”]
    ]
    输出: 6

    PS:
    使用单调栈方法求解(同84)

    class Solution {
          public int maximalRectangle(char[][] matrix) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
            int[] height = new int[matrix[0].length];
            int globalmax = 0;
            for (int i = 0; i < matrix.length; i++){
                for (int j = 0; j < matrix[0].length; j++){
                    if (matrix[i][j] == '0') height[j] = 0;
                    else height[j]++;
                }
                globalmax = Math.max(globalmax, maxrow(height));
            }
            return globalmax;
        }
        public int maxrow(int[] height){
            Stack<Integer> st = new Stack<>();
            int localmax = 0;
            for (int i = 0; i <= height.length; i++){
                int h = (i == height.length)? 0 : height[i];
                while (!st.isEmpty() && height[st.peek()] >= h){
                    int maxheight = height[st.pop()];
                    int area = st.isEmpty()? i * maxheight : maxheight * (i - st.peek() -1);
                    localmax = Math.max(localmax, area);
                }
                st.push(i);
            }
            return localmax;
        }
    }
    
  • 相关阅读:
    tar命令,vi编辑器
    Linux命令、权限
    Color Transfer between Images code实现
    利用Eclipse使用Java OpenCV(Using OpenCV Java with Eclipse)
    Matrix Factorization SVD 矩阵分解
    ZOJ Problem Set
    Machine Learning
    ZOJ Problem Set
    ZOJ Problem Set
    ZOJ Problem Set
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075588.html
Copyright © 2011-2022 走看看