74.Maximal Rectangle(数组中的最大矩阵)
2024-10-07 13:32:47
Level:
Hard
题目描述:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
思路分析:
我们的解题思路可以转换成求解Largest Rectangle in Histogram这道题的思路,假设有一个二维数组:
1 1 0 1 0 1
0 1 0 0 1 1
1 1 1 1 0 1
1 1 1 1 0 1
首先初始height数组为1 1 0 1 0 1,它是二维数组第一行的复制,然后我们很容易得到最大的面积为2,然后我们升级数组,我们扫描第二行,当我们遇到matrix[1] [i]为0时,我们设置height[i]为0,否则设置height[i]=height[i]+1;这意味着height增加了1,因此height数组变成了0 2 0 0 1 2。此时最大的面积也为2。应用同样的方法直到扫描完整个数组,最后height数组为 2 4 2 2 0 4,因此最大的矩阵面积为2*4=8。
代码:
public class Solution{
public int maximalRectangle(char [][]matrix){
if(matrix==null||matrix.length==0)
return 0;
int []height=new int [matrix[0].length]; //构造高度数组
for(int i=0;i<matrix[0].length;i++){
if(matrix[0][i]=='1')
height[i]=1;
else
height[i]=0;
}
int res=largestarea(height);
for(int i=1;i<matrix.length;i++){
resetheight(matrix,height,i); //更新高度数组
res=Math.max(res,largestarea(height)); //更新最大的矩形面积
}
return res;
}
public void resetheight(char[][]matrix,int []height,int i){
for(int j=0;j<matrix[0].length;j++){
if(matrix[i][j]=='1')
height[j]=height[j]+1;
else
height[j]=0;
}
}
public int largestarea(int []height){
if(height==null||height.length==0)
return 0;
Stack<Integer>s=new Stack<>();
int maxarea=0;
for(int i=0;i<=height.length;i++){
int h=(i==height.length)?0:height[i]; //最后添加一个零是为了能让栈中最后一个元素弹出
if(s.isEmpty()||h>=height[s.peek()]){
s.push(i);
}else{
int temp=s.pop();
maxarea=Math.max(maxarea,height[temp]*(s.isEmpty()?i:(i-s.peek()-1)));
i--;
}
}
return maxarea;
}
}
最新文章
- ubuntu系统虚拟机下共享文件夹
- EnableViewState
- Linux下memcached安装和启动方法
- haskell debug
- redis在centOS的安装
- jquery.autocomplete.js 两种实现方法
- iOS 在类实现定义中声明成员变量的怪异方式
- uva 10916 Factstone Benchmark(对数函数的活用)
- php mkdir 创建多级目录实例代码
- Android 流媒体系列(一)
- 汽车Vin码识别——可以嵌入到手机里的新OCR识别技术
- html页面不使用缓存的代码
- Angular JS的正确打开姿势——简单实用(上)
- Numpy&;Pandas
- Input子系统(二)【转】
- CISCO 关闭4786端口解决方法
- Android 深入浅出 - manifest文件的使用
- AT24Cxx(EEPROM)子系统
- Linux-vi/vim编辑器常用命令与用法
- hibernate 性能优化之 1+N 问题