85. Maximal Rectangle H

来源:互联网 发布:股票价值计算软件 编辑:程序博客网 时间:2024/05/18 02:07

这题是Largest Rectangle in Histogram的改编 http://blog.csdn.net/sinat_29621543/article/details/52529818 ,使用堆栈复杂度为O(n^2),分治算法复杂度为O(n^2logn)

原题:

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.

下面算法使用堆栈

public class Solution {    public static int maximalRectangle(char[][] matrix) {        if(matrix.length == 0){            return 0;        }        int x,y,area;        int maxarea = 0;        int[] height = new int[matrix[0].length+1];        int se;        int tempy;        for(y = 0; y<matrix.length ;++y){            Stack<Integer> stack = new Stack<Integer>();            for(x = 0; x<=matrix[0].length; ++x){                if(height[x]!=0){                    height[x] -= 1;                }else{                    tempy = y;                    while(x < matrix[0].length && tempy < matrix.length && matrix[tempy][x] == '1'){                        ++height[x];                        ++tempy;                    }                }                while(!stack.isEmpty() && height[stack.peek()]>height[x]){                    se = stack.pop();                    area = stack.isEmpty()?height[se]*(x):(x - stack.peek() - 1)*height[se];                    if(area>maxarea){                        maxarea = area;                    }                }                stack.push(x);            }        }return maxarea;    }    }


0 0
原创粉丝点击