leetCode练习(85)
来源:互联网 发布:php时间月份差 编辑:程序博客网 时间:2024/04/28 02:21
题目:Maximal Rectangle
难度: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.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 6.解题思路:
求最大全1矩形。可以化简为84题的子问题。参考第84题。以上图为例,以此计算0-0层,0-1层,0-2层····0-4层的最大矩阵即可。
具体代码如下:
public class h_85_MaximalRectangle {public static int maximalRectangle(char[][] matrix) { int[] temp=new int[matrix[0].length]; int res=0; int temp2; if(matrix.length==0||matrix[0].length==0){ return 0; } for(int i=0;i<temp.length;i++){ temp[i]=0; } for(int i=0;i<matrix.length;i++){ for(int j=0;j<temp.length;j++){ if(matrix[i][j]=='0'){ temp[j]=0; }else{ temp[j]=1+temp[j]; } } for(int w:temp){ System.out.print(w+" "); } System.out.println(); temp2=largestRectangleArea(temp); System.out.println(i+":"+temp2); res=res>temp2?res:temp2; } return res; }public static int largestRectangleArea(int[] heights) { int len=heights.length; int res=0; int temp; int left=0,right=0; int i; Stack<Integer> stack=new Stack<>(); for(i=0;i<len;i++){ if(stack.isEmpty()){ stack.push(i); continue; } while(!stack.isEmpty()){ if(heights[stack.peek()]<=heights[i]){ break; }else{ temp=stack.pop(); right=i-1; if(stack.isEmpty()){ left=0; }else{ left=stack.peek()+1; } res=res>(right-left+1)*heights[temp]?res:(right-left+1)*heights[temp]; } } stack.push(i); } while(!stack.isEmpty()){ int top=heights[stack.pop()]; int size=top*(stack.isEmpty()?i:i-stack.peek()-1); res=Math.max(res, size); } return res; }public static void main(String[]args){char[][] a=new char[4][5];char[]nums1={'1','0','1','0','0'};char[]nums2={'1','0','1','1','1'};char[]nums3={'1','1','1','1','1'};char[]nums4={'1','0','0','1','0'};a[0]=nums1;a[1]=nums2;a[2]=nums3;a[3]=nums4;maximalRectangle(a);}}
0 0
- leetCode练习(85)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- php源码之路第二章第二节(SAPI概述之嵌入式)
- VideoView实现视频引导页效果
- Android常用控件——AlertDialog
- Shiro 的使用简单Demo +MVC
- PC机主板蜂鸣器报警提示整理
- leetCode练习(85)
- Java基础4——数组
- 类名反射&&方法反射
- Makefile 学习小记(二)
- hdu 1878 欧拉回路
- 关于更改MySQL默认字符编码的问题
- 类成员函数解析
- awk读取文件里面的某个字段
- 清华EMBA课程系列思考之十三(1) -- 企业传播学