leetcode -- 85. 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.
Example:
Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

AC代码

参考自:https://leetcode.com/problems/maximal-rectangle/discuss/231921/Simple-Java-Solution-based-on-84.-Largest-Rectangle-in-Histogram

class Solution {
	// 首先,也是用dp做:heights保存某一列从上数第i行的连续的'1'的个数;
    // 然后使用84的逻辑,取连续区间最大的矩形大小就可以了;
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return 0;
        int width = matrix[0].length, res = 0;
        int[] heights = new int[width];
        for (char[] row : matrix) {
            for (int c = 0; c < width; c++) {
                if (row[c] == '1') heights[c]++;
                else heights[c] = 0;
            }
            res = Math.max(res, largestRectangleArea(heights));
        }
        return res;
    }
    
	// 以下部分是第84题的解法:分治求最大矩形(不需要修改)
    // 思路:对于每一段区间,都存在一个最小值
		// 对于最小值,无非就是三种可能:
		// 1:要么整段面积最大,2、3:要么最小值左边或者最小值右边(均不包含最小值)的面积最大,采用分治法递归解决;
		// 遇到有序排列的区间,采用递归会降低效率,于是只要单独计算并且比较就可以
	public int largestRectangleArea(int[] heights) {
        return largestRect(heights, 0, heights.length - 1);
    }
	
    private int largestRect(int[] heights, int start, int end) {
        if (start > end) return 0;
        if (start == end) return heights[start];
        int minIndex = start;
        // 使用是否有序排列的变量可以显著提高效率
        // 这里可以检测双向(变大或者变小的顺序)
        int inc = 0, dec = 0;
        for (int i = start + 1; i <= end; i++) {
            if (heights[i] < heights[minIndex]) minIndex = i;
            if (heights[i] > heights[i - 1]) inc++; // 升序
            else if (heights[i] < heights[i - 1]) dec--; // 降序
        }
        int res = 0;
        // 升序
        if (dec == 0) {
            for (int i = start; i <= end; i++)
                res = Math.max(res, heights[i] * (end - i + 1));
        } // 降序
        else if (inc == 0) {
            for (int i = start; i <= end; i++)
                res = Math.max(res, heights[i] * (i - start + 1));
        } // 无序
        else {
            res = Math.max(Math.max(largestRect(heights, minIndex + 1, end), largestRect(heights, start, minIndex - 1)),
                    heights[minIndex] * (end - start + 1));
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值