LeetCode 85 (Maximal-Rectangle)java
来源:互联网 发布:如何做好一个淘宝运营 编辑:程序博客网 时间:2024/05/22 11:57
原题: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的最大长方形的面积;
昨天AC84的时候想到了这个解法,想再查一下有没有其他的解法,看了一下大部分还是利用84题的结论,所以我在代码中取巧,直接调了84的函数,结果通过;
思路:在84题中,我们求得了给定数组中最大矩形的面积,这道题我们可以这样考虑,必须以某一行为底的情况下,最大的长方形面积是多少,再循环遍历行即可;而以某行为底的长方形面积就可以转化为数组中最大长方形面积;我们这样构建数组,当某位置元素为0,数组值为0,若为1,数组值为上面有多少个连续的1;
代码:其中第二个函数取自84题;
/*Author:JassyTime:2016/11/25Number:LeetCode 85 (Maximal Rectangle)Source: http://oj.leetcode.com/problems/maximal-rectangle/ Result:ACConclusion:*/public class Solution { public int maximalRectangle(char[][] matrix) { //求必须以某一行为底的情况下,最大的长方形; if(matrix.length==0){ return 0; } int rows=matrix.length; int cols=matrix[0].length; //tmp数组存储以该行为底,上面每列有多少个1,那么代入84题代码,得到的面积就是85题中面积,设置全局变量maxArea记录最大面积; int[] tmp=new int[cols]; int maxArea=0; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ if(matrix[i][j]=='0'){ tmp[j]=0; }else{ tmp[j]+=1; } } maxArea=maxArea>Solution.largestRectangleArea(tmp)?maxArea:largestRectangleArea(tmp); } return maxArea; } static int largestRectangleArea(int[] heights) { if(heights.length==0){ return 0; } int[] leftMin=new int[heights.length]; int[] rightMin=new int[heights.length]; leftMin[0]=-1; rightMin[heights.length-1]=heights.length; //得到左边数组; for(int i=1;i<heights.length;i++){ if(heights[i]>heights[i-1]){ leftMin[i]=i-1; }else{ int p=leftMin[i-1]; while(p>=0 && heights[i]<=heights[p]){ p=leftMin[p]; } leftMin[i]=p; } } //得到右边数组; for(int i=heights.length-2;i>=0;i--){ if(heights[i]>heights[i+1]){ rightMin[i]=i+1; }else{ int p=rightMin[i+1]; while(p<heights.length && heights[i]<=heights[p]){ p=rightMin[p]; } rightMin[i]=p; } } //计算; int area=0; for(int i=0;i<heights.length;i++){ area=Math.max(area,(rightMin[i]-leftMin[i]-1)*heights[i]); } return area; }}
0 0
- LeetCode 85 (Maximal-Rectangle)java
- [Leetcode] Maximal Rectangle (Java)
- [LeetCode][Java] Maximal Rectangle
- Maximal Rectangle leetcode java
- 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
- LeetCode 85 Maximal Rectangle
- [Leetcode] #85 Maximal Rectangle
- [Leetcode 85] Maximal Rectangle
- [leetcode-85]Maximal Rectangle(c++)
- Leetcode 85 - Maximal Rectangle(dp)
- [leetcode]85. Maximal Rectangle(Java)
- [leetcode 85] Maximal Rectangle 待续
- 正则表达式实例
- 工作空闲时整理的一些笔记
- [编程题] 优雅的点--网易
- MongoDB安装教程
- bzoj 1415 [Noi2005]聪聪和可可 概率dp
- LeetCode 85 (Maximal-Rectangle)java
- linux系统svn服务器搭建
- Eclipse project 重命名问题(如何彻底修改工程名)
- iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单
- simulink(转载)
- iOS中cell自适应文本Label高度篇
- Bootstrap3 表格-状态类
- Ubuntu下ssh远程链接传输
- 高德地图添加Markers不显示的问题