leetcode85 - Maximal Rectangle - hard

來源:互聯網
上載者:User

標籤:pop   lse   empty   new   合格   int   contain   code   private   

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  Iterative的largest rectangle in histogram.思路:一層一層遍曆,到i層時,第i層是1的位置可以向上延伸所有連續的1作為一個直方條條,按這樣的規律可以把matrix[0:i][:]看做一個長條圖,然後去統計當前情況下的最大rectangle,得到答案後去打擂台。所有層遍曆完了,答案就出來了。 長條圖的儲存:用int[] heights[colLength]來儲存,更新的方法是,掃matrix裡新的一行時,如果看到’0’就清空heights[j],如果看到’1’就讓heights[j]++。解釋計算長條圖裡的清空操作:直方條的定義是底部非空向上生長。因為histogram問題裡能用stack解決的原因就是,所有長條圖最底部開始都是非空的,那麼算面積是可以只在意頂上高到哪裡,不用擔心底部有沒有懸空,從而記錄高度即可。如果你把matrix的局部轉化成長條圖的時候看到上面有1但底部是0,那這一列都不合格直方條的定義了。上面的1不用擔心,你之前遍曆到前面那行的時候算過了。 相關題目:Largest Rectangle in Histogram。  https://www.cnblogs.com/jasminemzy/p/9764297.html 實現:
class Solution {    public int maximalRectangle(char[][] matrix) {        // invalid input.        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {            return 0;        }                int ans = 0;        int[] heights = new int[matrix[0].length];        for (int i = 0; i < matrix.length; i++) {            for (int j = 0; j < matrix[0].length; j++) {                if (matrix[i][j] == ‘0‘) {                    heights[j] = 0;                } else {                    heights[j]++;                }            }            ans = Math.max(ans, maxRecInHistogram(heights));        }        return ans;    }        private int maxRecInHistogram(int[] heights) {        int ans = 0;        Stack<Integer> stack = new Stack<>();        for (int i = 0; i <= heights.length; i++) {            while (!stack.isEmpty() && (i == heights.length || heights[i] < heights[stack.peek()])) {                int height = heights[stack.pop()];                int width = stack.isEmpty() ? i : i - stack.peek() - 1;                ans = Math.max(ans, height * width);            }            stack.push(i);        }        return ans;    }}

 

leetcode85 - Maximal Rectangle - hard

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.