LeetCode 85. Maximal Rectangle

原题链接在这里:https://leetcode.com/problems/maximal-rectangle/

题目:

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

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.

题解:

用数组heights存储一行中值为1的点的最大高度, 然后像Largest Rectangle in Histogram算这一行能产生的最大面积maxRec.

Time Complexity: O(m * n). m = matrix.length. n = matrix[0].length. Calculate area takes O(n) time, but it is within outer i loop, not inner j loop.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int maximalRectangle(char[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 4             return 0;
 5         }
 6         
 7         int m = matrix.length;
 8         int n = matrix[0].length;
 9         int [] heights = new int[n];
10         int res = 0;
11         
12         for(int i = 0; i < m; i++){
13             for(int j = 0; j < n; j++){
14                 heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0;
15             }
16             
17             res = Math.max(res, calArea(heights));    
18         }
19         
20         return res;
21     }
22     
23     private int calArea(int [] heights){
24         if(heights == null || heights.length == 0){
25             return 0;
26         }
27         
28         Stack<Integer> stk = new Stack<>();
29         stk.push(-1);
30         int res = 0;
31         
32         for(int i = 0; i < heights.length; i++){
33             while(stk.peek() != -1 && heights[stk.peek()] >= heights[i]){
34                 int h = heights[stk.pop()];
35                 int w = i - stk.peek() - 1;
36                 res = Math.max(res, h * w);
37             }
38             
39             stk.push(i);
40         }
41         
42         while(stk.peek() != -1){
43             int h = heights[stk.pop()];
44             int w = heights.length - stk.peek() - 1;
45             res = Math.max(res, h * w);
46         }
47         
48         return res;
49     }
50 }

类似Largest Rectangle in Histogram.

posted @ 2015-09-17 22:55  Dylan_Java_NYC  阅读(482)  评论(0)    收藏  举报