您的位置:首页 > 其它

LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

2013-07-20 23:17 549 查看
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

public int maximalRectangle2(char[][] matrix) {
int m = matrix.length;
int n = m == 0 ? 0 : matrix[0].length;
int[][] height = new int[m][n + 1];
//actually we know that height can just be a int[n+1],
//however, in that case, we have to write the 2 parts together in row traverse,
//which, leetcode just doesn't make you pass big set
//所以啊,leetcode是喜欢分开写循环的,即使时间复杂度一样,即使可以节约空间
int maxArea = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '0'){
height[i][j] = 0;
}else {
height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
}
}
}
for(int i = 0; i < m; i++){
int area = maxAreaInHist(height[i]);
if(area > maxArea){
maxArea = area;
}
}
return maxArea;
}

private int maxAreaInHist(int[] height){
Stack<Integer> stack = new Stack<Integer>();
int i = 0;
int maxArea = 0;
while(i < height.length){
if(stack.isEmpty() || height[stack.peek()] <= height[i]){
stack.push(i++);
}else {
int t = stack.pop();
maxArea = Math.max(maxArea, height[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return maxArea;
}


View Code
这里有一个和leetcode相关的细节。就是本来在计算height数组的时候,我们没有必要分配成代码中的那个样子,一维就可以了,然后在遍历每一行的时候计算当前行的height数组,然后再计算maxArea。这种情况下还是过不了大集合,所以不得不为每一行都保存一个height,先期计算该二维数组。

总结:

1. 学到的新知识要用;

2. 画面感和逻辑分析都很重要,不可偏非。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: