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.
View Code
这里有一个和leetcode相关的细节。就是本来在计算height数组的时候,我们没有必要分配成代码中的那个样子,一维就可以了,然后在遍历每一行的时候计算当前行的height数组,然后再计算maxArea。这种情况下还是过不了大集合,所以不得不为每一行都保存一个height,先期计算该二维数组。
总结:
1. 学到的新知识要用;
2. 画面感和逻辑分析都很重要,不可偏非。
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. 画面感和逻辑分析都很重要,不可偏非。
相关文章推荐
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用](最大矩形)
- leetcode解题笔记:Two sum系列解题思路
- [LeetCode]Array主题系列{1,11,15,16,18,26,27,31,33,34题}
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
- LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]
- LeetCode 18 4Sum K-sum系列
- LeetCode 笔记系列三 3Sum
- Swift学习笔记系列——(18)造型
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
- LeetCode 笔记系列 14 N-Queen II [思考的深度问题]
- LeetCode 笔记系列 19 Scramble String [合理使用递归]
- leetcode笔记--Best Time to Buy and Sell Stock系列(I,II, III, IV)
- LeetCode 笔记系列11 First Missing Positive [为什么我们需要insight]
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 笔记系列二 Container With Most Water
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
- LeetCode 笔记系列九 Search in Rotated Sorted Array
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 18 4Sum K-sum系列
- Hadoop系列修炼---入门笔记18