【leetcode刷題筆記】Maximal Rectangle

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   2014   for   re   

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

 

題解,很巧妙的一道題,對於一個0-1矩陣,它的每一行及以上都可以看作一個長條圖(如所示),利用Largest Rectangle in Histogram的方法,可以在O(n)的時間搜尋出這一行及以上的長條圖中面積最大的矩形,對矩陣的每一行依次做這個操作,就可以在O(n2)的時間搜尋出最大的矩形了。

將原矩陣轉換成長條圖矩陣的方法:設用transfer矩陣存放轉換後的長條圖,則

transfer[0][j] = matrix[0][j] - ‘0‘;transfer[i][j] = (matrix[i][j] == ‘0‘ ? 0: transfer[i-1][j] + 1); (i >= 1)

代碼如下:

 1 public class Solution { 2     public int largestRectangleArea(int[] height) { 3         if(height == null || height.length == 0) 4             return 0; 5         Stack<Integer> index = new Stack<Integer>(); 6         int totalMax = 0; 7         ArrayList<Integer> newHeight = new ArrayList<Integer>(); 8         for(int i:height) newHeight.add(i); 9         newHeight.add(0);10         11         12         for(int i = 0;i < newHeight.size();i++){13             if(index.isEmpty() || newHeight.get(i) >= newHeight.get(index.peek()))14                 index.push(i);15             else{16                 int top = index.pop();17                 totalMax = Math.max(totalMax,newHeight.get(top) * (index.isEmpty()?i:i-index.peek()-1));18                 i--;19             }20         }21         22         return totalMax;23     }24     public int maximalRectangle(char[][] matrix) {25         if(matrix == null || matrix.length == 0)26             return 0;27         int m = matrix.length;28         int n = matrix[0].length;29         int totalMax = 0;30         int[][] transfer = new int[m][n];31         32         //transform matrix to histogram in a new matrix33         for(int i = 0;i < n;i++)34             transfer[0][i] = matrix[0][i]- ‘0‘;35         for(int i = 1;i < m;i++){36             for(int j = 0;j < n;j++){37                 if(matrix[i][j] == ‘0‘ )38                     transfer[i][j] = 0;39                 else {40                     transfer[i][j] = transfer[i-1][j] + 1; 41                 }42             }43         }44         45         //Using histogram to find the biggest rectangle46         for(int i = 0;i < m;i++){47             totalMax = Math.max(totalMax, largestRectangleArea(transfer[i]));48         }49         50         return totalMax;51     }52 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.