Leetcode -- Maximal Rectangle
来源:互联网 发布:淘宝购物车营销在哪 编辑:程序博客网 时间:2024/06/06 17:09
https://oj.leetcode.com/problems/maximal-rectangle/
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 maximalRectangle(char[][] matrix)
Leetcode 把这一题放在Largest Rectangle这一题后面其实就是这一题最大的提示了。
这一题的做法如果没有思路的话是很难的,基本上你很难在不expensive的情况下画清楚一个范围是否矩形。但上一题就给了一个合适的解法。
实际上这一题做法在懂的上一题之后就变得很简单了。其实就是从第一层扫到最后一层,不停构建供给上一题用的histogram,然后根据上一题的解法一行行的解就可以了。
给出代码如下:
public int maximalRectangle(char[][] matrix) { if(matrix.length == 0 || matrix[0].length == 0) return 0; int[] cur_histogram = new int[matrix[0].length]; int res = 0; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ if(matrix[i][j] == '0') cur_histogram[j] = 0; else cur_histogram[j]++; } res = Math.max(res, maxRectinHistogram(cur_histogram)); } return res; } public int maxRectinHistogram(int[] height){ Stack<Integer> index_stack = new Stack<Integer>(); int res = 0; for(int i = 0; i < height.length; i++){ if(index_stack.isEmpty() || height[i] >= height[index_stack.peek()]) index_stack.push(i); else{ while(!index_stack.isEmpty() && height[index_stack.peek()] > height[i]){ int cur_bar = index_stack.pop(); int prev_bar = index_stack.isEmpty() ? -1 : index_stack.peek(); res = Math.max(res, height[cur_bar] * (i - prev_bar - 1)); } index_stack.push(i); } } while(!index_stack.isEmpty()){ int cur_bar = index_stack.pop(); int prev_bar = index_stack.isEmpty() ? -1 : index_stack.peek(); res = Math.max(res, height[cur_bar] * (height.length - prev_bar - 1)); } return res; }
0 0
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- LeetCode: Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode: Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [leetcode] Maximal Rectangle
- [LeetCode]Maximal Rectangle
- [leetcode]Maximal Rectangle
- LeetCode-Maximal Rectangle
- [leetcode] Maximal Rectangle
- Leetcode Maximal Rectangle
- [LeetCode] Maximal Rectangle
- leetcode Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode | Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [Leetcode] Maximal Rectangle (Java)
- 译自five popular myths about c++ --by Bjarne Stroustrup (3)
- stringstream对象的使用
- Volley封装,一行代码搞定http请求(重点介绍cookie、https、自定义requst请求)
- oracle扩展表空间
- 企业开发
- Leetcode -- Maximal Rectangle
- android开发之高仿中国建设银行App
- eclipse安装ajdt插件后:java.lang.NoClassDefFoundError: test/HelloWord
- VS回写Teamcity版本号
- 高手是有理由的
- 支付宝 ALI129 错误
- How to show related products in product view page with magento?
- JScrollPane+JTree的使用+container 是JPanel
- 图像放缩中最近邻插值和双线性插值的基本原理