zoukankan      html  css  js  c++  java
  • [leetcode] Maximal Rectangle

    Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

    https://oj.leetcode.com/problems/maximal-rectangle/

    思路:转化成每一行求 Largest Rectangle in Histogram

    import java.util.Stack;
    
    public class Solution {
        public int maximalRectangle(char[][] matrix) {
            if (matrix.length == 0 || matrix[0].length == 0)
                return 0;
    
            int m = matrix.length;
            int n = matrix[0].length;
            int res = 0;
    
            for (int i = 0; i < m; i++) {
                int[] height = new int[n];
                for (int j = 0; j < n; j++) {
                    if (matrix[i][j] == '1') {
                        height[j]++;
                        for (int k = i - 1; k >= 0; k--) {
                            if (matrix[k][j] == '1')
                                height[j]++;
                            else
                                break;
                        }
                    }
                }
                res = Math.max(res, largestRectangleArea(height));
            }
    
            return res;
    
        }
    
        private int largestRectangleArea(int[] height) {
            Stack<Integer> stack = new Stack<Integer>();
            int maxArea = 0;
            for (int i = 0; i < height.length;) {
                if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
                    stack.push(i++);
                } else {
                    int start = stack.pop();
                    int width = stack.isEmpty() ? i : (i - stack.peek() - 1);
                    maxArea = Math.max(maxArea, height[start] * width);
                }
    
            }
    
            while (!stack.isEmpty()) {
                int start = stack.pop();
                int width = stack.isEmpty() ? height.length : (height.length - stack.peek() - 1);
                maxArea = Math.max(maxArea, height[start] * width);
            }
    
            return maxArea;
        }
    
        public static void main(String[] args) {
            char[][] matrix = new char[][] { { '0', '0', '1', '0' }, { '0', '0', '0', '1' }, { '0', '1', '1', '1' },
                    { '0', '0', '1', '1' } };
            System.out.println(new Solution().maximalRectangle(matrix));
    
        }
    }
    View Code

    第二遍记录: 

    参考:

    http://blog.csdn.net/doc_sgl/article/details/11832965

  • 相关阅读:
    spring MVC配置详解
    使用JDBC连接各种数据库
    Linux Shell常用shell命令
    IOS返回go(-1)
    NFS客户端挂载
    oracle常用函数
    支付宝手机网站支付流程(Node实现)
    SQL中的case when then else end用法
    mysql
    socket
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3815885.html
Copyright © 2011-2022 走看看