leetcodehard 模式专杀之85. Maximal Rectangle
来源:互联网 发布:ubuntu flash命令行 编辑:程序博客网 时间:2024/06/07 03:49
这道题没有自己想出来,参考了网上的思路,基本上就是分两部,把求最大面积全1矩阵的问题转化为84. Largest Rectangle in Histogram, 尼玛难怪这两题是相连的,而且两道都是hard模式,如果没做出来84直接做85,还真是有些坑爹呢,看来leetcode最好还是按顺序做比较好。至于84怎么做这个我下一期再出解释吧,咱这里就先假设已经有这么一个现成的算法解决了84(事实上我这里用的函数通不过84的时间复杂度检测,也就是说,不是最优的)。那么解决85的思路就是把原始矩阵转化成histogram(柱状图)表示,这个过程只要按列做一个线性累加就好,具体看代码,然后从第一行到最后一行,解决84问题,每解决一个子84问题得到一个返回结果,最终返回最大的那个即可。不废话,上代码:
class Solution { public int maximalRectangle(char[][] matrix) { if(matrix==null || matrix.length<1){ return 0; } int row = matrix.length; int col = matrix[0].length; int[][] histogram = new int[row][col]; for(int i = 0; i<row; i++){ for(int j = 0; j<col; j++){ histogram[i][j] = calcHistogram(matrix, i , j); } } int max = 0; for(int i = 0; i<row; i++) { List<Integer> partList = new ArrayList<>(); for (int j = 0; j < col; j++) { if (histogram[i][j] == 0) { if(j>0 && histogram[i][j-1]!=0){ int area = calcArea(partList); if(area>max){ max = area; } partList.clear(); } } else { partList.add(histogram[i][j]); if (j == col - 1) { int area = calcArea(partList); if (area > max) { max = area; } } } } } return max; } public static int calcArea(List<Integer> ll){ int len=ll.size(); int max_size=0; for(int i=0;i<len;i++) { int min_height=ll.get(i); int current_size=min_height; for(int j=i;j<len;j++) { if(ll.get(j)<min_height){ min_height=ll.get(j); } current_size=min_height*(j-i+1); if(current_size>max_size) max_size=current_size; } } return max_size; } public static int calcHistogram(char[][] matrix, int i, int j){ if (matrix[i][j] == '0'){ return 0; }else{ int z = 0; for(int k = i; k<matrix.length; k ++){ if(matrix[k][j]=='0'){ break; }else{ z++; } } return z; } }}
阅读全文
0 0
- leetcodehard 模式专杀之85. Maximal Rectangle
- leetcode之Maximal Rectangle
- LeetCode之Maximal Rectangle
- LeetCode 85. Maximal Rectangle
- [Leetcode] 85. Maximal Rectangle
- LeetCode --- 85. Maximal Rectangle
- [LeetCode]*85.Maximal Rectangle
- 85. Maximal Rectangle
- [leetcode] 85.Maximal Rectangle
- Leetcode 85. Maximal Rectangle
- 85. Maximal Rectangle
- leetcode 85. Maximal Rectangle
- LeetCode 85. Maximal Rectangle
- Leetcode 85. Maximal Rectangle
- Leetcode:85. Maximal Rectangle
- LeetCode 85. Maximal Rectangle
- LeetCode-85.Maximal Rectangle
- leetcode.85. Maximal Rectangle
- 如何查看本机的外网IP
- 网页编程--JavaScript之表单校验
- Java基础之集合框架--Arrays工具类(专门操作数组的工具类)
- (四)-对象内存的分配策略
- springmvc配置文件
- leetcodehard 模式专杀之85. Maximal Rectangle
- JS——面向对象高级
- 线程的生命周期和状态控制
- SpringBoot全局异常捕捉
- redis总结
- 深入理解java异常处理机制
- sleep()与wait()的区别
- 简单的顺序表,及其5大功能的实现!!!
- 分布式事务?No, 最终一致性