码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 85] Maximal Rectangle (华为2015机试)

时间:2015-04-12 13:28:40      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:java   算法   leetcode   华为   

题目链接:maximal-rectangle


import java.util.Arrays;

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

public class MaximalRectangle {

//	65 / 65 test cases passed.
//	Status: Accepted
//	Runtime: 292 ms
//	Submitted: 0 minutes ago
	//时间复杂度O(n ^ 2), 空间复杂度 O(n)
    public int maximalRectangle(char[][] matrix) {
    	if(matrix.length == 0) {
        	return 0;
        }
    	int m = matrix.length;
    	int n = matrix[0].length;
        int[] H = new int[n];
        int[] L = new int[n];
        int[] R = new int[n];
        Arrays.fill(H, 0);
        Arrays.fill(L, 0);
        Arrays.fill(R, n);
        
        int ret = 0;
        for(int i = 0; i < m; ++i) {
        	int left = 0;
        	int right = n;
        	
        	for (int j = 0; j < n; j++) {
				if (matrix[i][j] == '1') {
					++H[j];
					L[j] = Math.max(L[j], left);
				} else {
					left = j + 1;
					H[j] = 0;
					L[j] = 0;
					R[j] = n;
				} 
			}
        	
        	for (int j = n - 1; j >= 0; j --) {
				if (matrix[i][j] == '1') {
					R[j] = Math.min(R[j], right);
					ret = Math.max(ret, H[j] * (R[j] - L[j]));
				} else {
					right = j;
				} 
			}
        }
        return ret;
        
    }
}    



华为2015机试题大概描述:

给定一个矩阵,里面只包含‘0’和‘1’,求出给最大的正方形的边长,该正方形里面全是‘1’


    public int maximalRectangle1(char[][] matrix) {
        if(matrix.length == 0) {
        	return 0;
        }
        int m = matrix.length;
    	int n = matrix[0].length;
        int[] H = new int[n];
        int[] L = new int[n];
        int[] R = new int[n];
        Arrays.fill(H, 0);
        Arrays.fill(L, 0);
        Arrays.fill(R, n);
        
        int maxLen = 0;
        for(int i = 0; i < m; ++i) {
        	int left = 0;
        	int right = n;
        	
        	for (int j = 0; j < n; j++) {
				if (matrix[i][j] == '1') {
					++H[j];
					L[j] = Math.max(L[j], left);
				} else {
					left = j + 1;
					H[j] = 0;
					L[j] = 0;
					R[j] = n;
				} 
			}
        	
        	for (int j = n - 1; j >= 0; j --) {
				if (matrix[i][j] == '1') {
					R[j] = Math.min(R[j], right);
					maxLen = Math.max(maxLen, Math.min(H[j], R[j] - L[j]));
				} else {
					right = j;
				} 
			}
        }
        return maxLen;
    }




[LeetCode 85] Maximal Rectangle (华为2015机试)

标签:java   算法   leetcode   华为   

原文地址:http://blog.csdn.net/ever223/article/details/45008667

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