zoukankan      html  css  js  c++  java
  • 20201226 最大矩形(困难)

    给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
    
     
    
    示例 1:
    
    
    输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
    输出:6
    解释:最大矩形如上图所示。
    示例 2:
    
    输入:matrix = []
    输出:0
    示例 3:
    
    输入:matrix = [["0"]]
    输出:0
    示例 4:
    
    输入:matrix = [["1"]]
    输出:1
    示例 5:
    
    输入:matrix = [["0","0"]]
    输出:0
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/maximal-rectangle
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    class Solution {
        public int maximalRectangle(char[][] matrix) {
            int m = matrix.length;
            if (m == 0) {
                return 0;
            }
            int n = matrix[0].length;
            int[][] left = new int[m][n];
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (matrix[i][j] == '1') {
                        left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
                    }
                }
            }
    
            int ret = 0;
            for (int j = 0; j < n; j++) { // 对于每一列,使用基于柱状图的方法
                int[] up = new int[m];
                int[] down = new int[m];
    
                Deque<Integer> stack = new LinkedList<Integer>();
                for (int i = 0; i < m; i++) {
                    while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) {
                        stack.pop();
                    }
                    up[i] = stack.isEmpty() ? -1 : stack.peek();
                    stack.push(i);
                }
                stack.clear();
                for (int i = m - 1; i >= 0; i--) {
                    while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) {
                        stack.pop();
                    }
                    down[i] = stack.isEmpty() ? m : stack.peek();
                    stack.push(i);
                }
    
                for (int i = 0; i < m; i++) {
                    int height = down[i] - up[i] - 1;
                    int area = height * left[i][j];
                    ret = Math.max(ret, area);
                }
            }
            return ret;
        }
    }
  • 相关阅读:
    android ListView美化-->几个比较特别的属性
    微博开发第一讲 知识点--2014.04.23
    ubuntu snap install 代理设置
    君正X2000开发板试用体验之二:君正X2000引导过程分析
    君正X2000开发板试用体验之一:开箱
    消除USB麦克风的电流声
    IT专业词汇中文译名探讨
    PCI/PCIE总线的历史
    龙芯派ejtag.cfg设置
    uos运行ejtag报错,找不到libreadline.so.6, libncurses.so.5, libusb-0.1.so.4
  • 原文地址:https://www.cnblogs.com/hbhb/p/14193849.html
Copyright © 2011-2022 走看看