`

Leetcode - Maximum Rectangle

 
阅读更多

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

[balabala] 这题想到借用Largest Rectangle in Histogram的思路就比较简单了。计算行 i 时,以这行为底,计算每一列对应的“高度”,若某列元素为0,则高度为0,若为1,则高度=同列上一行高度 + 1。得出每列高度后,应用Largest Rectangle in Histogram的思路计算出该行对应的直方图中的最大矩形。遍历完所有行后得解。

 

    //method 1
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int max = 0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[] h = new int[cols];
        LinkedList<Integer> stack = new LinkedList<Integer>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                h[j] = matrix[i][j] == '1' ? h[j] + 1 : 0;
            }
            int j = 0;
            stack.clear();
            while (j < cols || !stack.isEmpty()) {
                if (stack.isEmpty() || (j < cols && h[j] >= h[stack.peek()])) {
                    stack.push(j++);
                } else {
                    int currH = h[stack.pop()];
                    while (!stack.isEmpty() && currH == h[stack.peek()]) {
                        stack.pop();
                    }
                    max = Math.max(max, currH * (stack.isEmpty() ? j : (j - stack.peek() - 1)));
                }
            }
        }
        return max;
    }

    
    // method2: more clear
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[] h = new int[cols + 1];
        int max = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == '1')
                    h[j] += 1;
                else
                    h[j] = 0;
            }
            max = Math.max(max, getLargestRectangle(h));
        }
        return max;
    }
    
    // the last element in h[] is always 0
    private int getLargestRectangle(int[] h) {
        int max = 0;
        LinkedList<Integer> stack = new LinkedList<Integer>();
        int i = 0;
        while (i < h.length) {
            if (stack.isEmpty() || h[i] >= h[stack.peek()]) {
                stack.push(i++);
            } else {
                int currH = h[stack.pop()];
                while (!stack.isEmpty() && h[stack.peek()] == currH) {
                    stack.pop();
                }
                int left = stack.isEmpty() ? -1 : stack.peek();
                max = Math.max(max, currH * (i - left - 1));
            }
        }
        return max;
    }

 

分享到:
评论

相关推荐

    leetcode卡-Array-LeetCode-Solution:数组-LeetCode-解决方案

    如"最宽的水平条"(Largest Rectangle in Histogram)。 5. **前缀和与后缀和**:通过计算数组的累积和,可以快速求解区间和问题。例如"连续子数组的最大和"(Maximum Subarray)。 6. **动态规划**:数组问题常与...

    蓄水池算法leetcode-leetcode:leetcode

    largest-rectangle-in-histogram: 最长递增子序列: 最长公共自序列: Something about: best time to buy and sell stack: 单链表中的环,两个单链表的公共点。 populating-next-right-pointers-in-each-node-ii: ...

    LeetCode最全代码

    318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-...

    leetcode分类-LeetCode:力码

    Maximum Subarray Minimum Path Sum Unique Paths Unique Paths II Longest Palindromic Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal Rectangle...

    Leetcode题目+解析+思路+答案.pdf

    - **Maximum Subarray**:寻找数组中的最大子数组和。 - **Climbing Stairs**:模拟爬楼梯,每次可以爬1阶或2阶。 5. **回溯(Backtracking)**: - **Combination**:求解组合问题。 - **Subsets**:找出所有...

    lrucacheleetcode-leetcode:leetcode

    Rectangle Monotonic stack for 2d array 239. Sliding Window Maximum 255. Verify Preorder Sequence in Binary Search Tree 907. Sum of Subarray Minimums 二叉搜索树 99. Recover Binary Search Tree 109. ...

    LeetCode leetcode部分题解答代码实现

    * Maximum Subarray:给定一个数组,返回数组中的最大子数组和。这个题目需要使用动态规划的思想,将数组分解成更小的子数组,并找到最大子数组。 5. 回溯算法 回溯算法是一种非常重要的算法思想,LeetCode 中有很...

    LeetCode练习答案

    - **最大子数组和(Maximum Subarray)**: 给定一个整数数组,找到一个具有最大和的连续子数组(至少包含一个数),返回其最大和。 - **爬楼梯(Climbing Stairs)**: 每次可以爬1或2个台阶,求出爬上n阶楼梯的不同方法...

    3、动态规划必练题(含解法).pdf

    本篇将深入探讨动态规划在LeetCode上的一些经典问题及其解法。 1. **Min Cost Climbing Stairs** (最小成本爬楼梯) 问题描述:有若干个台阶,每次可以爬1阶或2阶,求达到顶部的最小成本。这是一个典型的动态规划...

Global site tag (gtag.js) - Google Analytics