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 0
Return 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
原创粉丝点击