LeetCode 85 Maximal Rectangle

这是一道很难的题,开始想用dp来解决,想了半天也没想通转移方程该怎么写,看了别人的博客才发现这道题可以和84题Largest Rectangle in Histogram 关联起来。把矩阵从上到下一行一行去切,只看上面的部分就可以发现其实可以转化成对每一行球第84题解的过程。但是我第84题是直接搜索每一列然后再左右搜索找到比那一列小的列为止然后计算通过的,这种复杂度比较高,我看了一下别人的解法,可以用栈来解决,这样问题只有线性的复杂度,然后对每行在求解,也不会有太高的时间复杂度。

代码如下:

class Solution {
    public int maximalRectangle(char[][] matrix) {
        
       int kuan=matrix.length;
        if (kuan==0) return 0;
       int chang=matrix[0].length;
       int max=0;
       int []height=new int[chang];
        for(int i=0;i<kuan;i++)
        {
            for (int j=0;j<chang;j++)
            {
                if (matrix[i][j]=='1')
                {
                    height[j]+=1;
                }
                else height[j]=0;
            }
            
            if (Cal(height)>max) max=Cal(height); 
        }
        return max; 
    }
    
        public int Cal(int []height)  //采用第84题的新解法(栈)来解决
    {
        Stack<Integer> stk=new Stack<Integer>();
        int max=0;
        for (int i=0;i<height.length;i++)
        {
            if (stk.empty()||height[i]>=stk.peek())
            {
                stk.push(height[i]);
            }
            else
            {
                int count=0;
                while (!stk.empty() && stk.peek()>height[i])
               {
                int index=stk.pop();
                    count++;
                if (count*index>max) max=count*index;
               }
                while (count!=0)
                {
                    count--;
                    stk.push(height[i]);
                }
               stk.push(height[i]);
            }
        }
        
        int count=0;
        while (!stk.empty())
        {
            int index=stk.pop();
            count++;
            if (count*index>max) max=count*index;   
        }
        return max;
        
    }
    
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值