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;
}
}

最新文章

  1. ubuntu系统虚拟机下共享文件夹
  2. EnableViewState
  3. Linux下memcached安装和启动方法
  4. haskell debug
  5. redis在centOS的安装
  6. jquery.autocomplete.js 两种实现方法
  7. iOS 在类实现定义中声明成员变量的怪异方式
  8. uva 10916 Factstone Benchmark(对数函数的活用)
  9. php mkdir 创建多级目录实例代码
  10. Android 流媒体系列(一)
  11. 汽车Vin码识别——可以嵌入到手机里的新OCR识别技术
  12. html页面不使用缓存的代码
  13. Angular JS的正确打开姿势——简单实用(上)
  14. Numpy&amp;Pandas
  15. Input子系统(二)【转】
  16. CISCO 关闭4786端口解决方法
  17. Android 深入浅出 - manifest文件的使用
  18. AT24Cxx(EEPROM)子系统
  19. Linux-vi/vim编辑器常用命令与用法
  20. hibernate 性能优化之 1+N 问题

热门文章

  1. 1、获取ip地址
  2. java并发学习--第六章 线程之间的通信
  3. 三、MyBatis-全局配置文件
  4. 了解卷积神经网络如何使用TDA学习
  5. struts2+jsp 遍历 &lt;s:iterator&gt;&lt;s:property&gt;
  6. NASA CEA 安装指南
  7. java生成128A条形码
  8. Primary Key Increase by Trigger
  9. 2018年第九届山东省ACM省赛总结
  10. 如何把word文档内容和图片直接导入到wordpress编辑器