leetcode85——最大矩形——java实现

题目分析:
在这里插入图片描述
分析:
这道题目其实就是84题的变种,如下图所示:
在这里插入图片描述
所以在本题中,我们只需要求出每个heights[i]的值,并调用84题中的方法即可。

具体代码如下:

class Solution {
   public int maximalRectangle(char[][] matrix) {
        if(matrix.length == 0)
            return 0;
        int[] heights = new int[matrix[0].length];
        int maxArea = 0;
        for(int row = 0; row < matrix.length; row ++) {
            for(int col = 0; col < matrix[0].length; col ++) {
                if(matrix[row][col] == '1') {
                    heights[col] ++;
                } else {
                    heights[col] = 0;
                }      
            }
            maxArea = Math.max(maxArea, largestRectangleArea(heights));
        }
        return maxArea;
    }
     
    public int largestRectangleArea(int[] heights) {
        return calculateArea(heights, 0, heights.length - 1);
    }
    
    public int calculateArea(int[] heights, int left, int right) {
        if (left > right)
            return 0;
        
        int minIndex = left;
        for(int i = left; i <= right; i ++) {
            if(heights[i] <= heights[minIndex])
                minIndex = i;
        }
        
        int area = (right - left + 1) * heights[minIndex];
        
        //递归
        int sidesArea = Math.max(calculateArea(heights, left, minIndex - 1), calculateArea(heights, minIndex + 1, right));
        return Math.max(area, sidesArea);
        /*int leftArea = calculateArea(heights, left, minIndex - 1);
        int rightArea = calculateArea(heights, minIndex + 1, right);
        
        return Math.max(area, Math.max(leftArea, rightArea));*/
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值