码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 085 Maximal Rectangle

时间:2015-05-19 20:39:59      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.

解题思路:

求01矩阵中,全是1的子矩阵的最大面积。

把矩阵按照每一行看做是直方图,可以转化为上一题,JAVA实现如下:

	static public int maximalRectangle(char[][] matrix) {
		if(matrix.length==0||matrix[0].length==0)
			return 0;
		int result=0;
		int[] dp=new int[matrix[0].length];
		for(int i=0;i<matrix.length;i++){
			for(int j=0;j<matrix[0].length;j++)
				if(matrix[i][j]==‘1‘)
					dp[j]++;
				else dp[j]=0;
			result=Math.max(result, largestRectangleArea(dp));
		}
		return result;
	}
	 public static int largestRectangleArea(int[] height) {
	        Stack<Integer> stk = new Stack<Integer>();
	        int ret = 0;
	        for (int i = 0; i <= height.length; i++) {
	            int h=0;
	            if(i<height.length)
	                h=height[i];
	            if (stk.isEmpty() || h >= height[stk.peek()])
	                stk.push(i);
	            else {
	                int top = stk.pop();
	                ret = Math.max(ret, height[top] * (stk.empty() ? i : i - stk.peek() - 1));
	                i--; 
	            }
	        }
	        return ret;
	}

 

Java for LeetCode 085 Maximal Rectangle

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4515359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!