leecode 解题总结:85. Maximal Rectangle

本文介绍了一种计算二维二进制矩阵中最大全为1的矩形区域面积的算法。该算法通过计算每一行的直方图高度并利用单调栈找到最大矩形面积。文章详细展示了如何使用C++实现这一过程。
class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty())
		{
			return 0;
		}
		int row = matrix.size();
		int col = matrix.at(0).size();
		vector<int> heights(col , 0);
		int maxArea = INT_MIN;
		int area;
		//计算以当前行及其向上的直方图的高度
		for(int i = 0 ; i < row ; i++)
		{
			for(int j = 0 ; j < col ; j++)
			{
				if('0' == matrix.at(i).at(j))
				{
					heights.at(j) = 0;
				}
				else if('1' == matrix.at(i).at(j))
				{
					heights.at(j)++;
				}
			}
			//计算当前行及其向上部分的直方图的面积
			area = largestRectangleArea(heights);
			maxArea = max(area , maxArea);
		}
		return maxArea;
    }

	//求最大矩形高度,用栈维护一个单调非递减区间的下标;当前元素 >= 栈顶对应高度, 将当前元素下标压入栈;
	//一旦遇到当前元素大于栈顶元素,则计算以栈顶高度为最小值的矩阵的最大面积,面积 = 栈顶对应高度 * (终点 - 起点 + 1)
	//终点=当前元素对应位置 - 1 , 起点=弹出栈顶后的新栈顶位置+1;不断弹出栈顶,直到当前元素 >= 栈顶对应高度
	int largestRectangleArea(vector<int>& heights)
	{
		if(heights.empty())
		{
			return 0;
		}
		int size = heights.size();
		stack<int> hists;
		int i = 0;
		int top;
		int width;
		int area = INT_MIN;
		while(i < size)
		{
			if(hists.empty() || heights.at(i) >= heights.at( hists.top() ))
			{
				hists.push(i++);
			}
			//需要计算最大面积
			else
			{
				top = hists.top();
				hists.pop();
				width = hists.empty() ? i : (i - 1 - hists.top());
				area = max(area , heights.at(top) * width);
			}
		}
		//将最后元素再做一次计算
		while(!hists.empty())
		{
			top = hists.top();
			hists.pop();
			width = hists.empty() ? i : (i - 1 - hists.top());
			area = max(area , heights.at(top) * width);
		}
		return area;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值