LeetCode_maximal-rectangle

题目描述:

 

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

主要是注意 公式中宽度的求取:

 

 

 

import java.util.*;
//本题是求直方图中最大矩形面积的变形
public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix==null||matrix.length==0||matrix[0].length==0)
            return 0;
        Stack<Integer> stack=new Stack<>();
        stack.push(-1);
        int row=matrix.length;
        int col=matrix[0].length;
        int high[]=new int[col];
        int max=0;
        for(int i=0;i<row;i++){
            //将点抽象成矩形的面积,构建模型
            for(int j=0;j<col;j++){
                if(matrix[i][j]=='0')
                    high[j]=0;
                else
                    high[j]+=1;
            }
            for(int j=0;j<col;j++){
                while(stack.peek()!=-1&&high[j]<high[stack.peek()]){
                    int topIndex=stack.pop();
                    max=Math.max(max,(j-1-stack.peek())*high[topIndex]);
                    /*一切都是为了这个公式做铺垫
                    一定要注意 宽度 是 j-1-stack.peek() 而不能用 j-topIndex 
                    因为 若存在栈中的两个下标中可能存在不连续的情况
                    出现不连续的情况的原因是 中间 断了的高度是高于 右边的
                    所以 求 删除节点的 面积的时候 ,是先 删除这个节点,然后找到删除节点的前一个节点,这两者中间的宽度才是真实的宽度!
                    */
                }
                stack.push(j);
            }
            while(stack.peek()!=-1){
                    int topIndex=stack.pop();
                    max=Math.max(max,(col-1-stack.peek())*high[topIndex]);
            }
        }
        return max;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值