【leetcode】85.(Hard)Maximal Rectangle

本文介绍了一种使用单调栈解决矩阵中寻找最大全'1'矩形的方法。通过为每一行创建高度数组并应用单调栈,实时更新最大矩形面积,最终返回矩阵中的最大矩形面积。

解题思路:
这道题是84题的拓展,还是用单调栈,然后每一排都求一次单调栈,并实时更新最大值即可。


提交代码:

class Solution {
	public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0||matrix[0].length==0)   return 0;
		int[][] heights = new int[matrix.length][matrix[0].length];
		Stack<Integer> stack=new Stack<Integer>();
		int maxSize=0;
		
		// create the total heights of each rows
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[0].length; j++) {
				if (i == 0) {
					if (matrix[i][j] == '1')
						heights[i][j] = 1;
					else
						heights[i][j] = 0;
				} else {
					if (matrix[i][j] == '1')
						heights[i][j] = heights[i - 1][j] + 1;
					else
						heights[i][j] = 0;
				}
			}
		}
		
		//calculate maxSize in each row
		for(int i=0;i<matrix.length;i++) {
			stack.clear();
			int j=0,curHeight,curLength,curSize;
			int[] h=new int[matrix[0].length+1];
			h=Arrays.copyOf(heights[i], matrix[0].length+1);
			
			
			while(j<h.length) {
				if(stack.isEmpty()||h[stack.peek()]<h[j])
					stack.push(j++);
				else {
					curHeight=h[stack.pop()];
					curLength=stack.isEmpty()?j:(j-stack.peek()-1);
					curSize=curHeight*curLength;
					if(curSize>maxSize)	maxSize=curSize;
				}
			}
		}
		return maxSize;
	}
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值