Leetcode 085 Maximal Rectangle(高效)

题目连接:Leetcode 085 Maximal Rectangle

解题思路:做过 Leetcode 084,这题就很简单了,将没一行都看作是一个数组,向上最大连续的1个数作为高。

class Solution {
	public:
		int largestRectangleArea(vector<int>& heights) {
			int n = heights.size();
			int* l = new int[n];
			int* r = new int[n];

			int* t = new int[n+1];
			int* p = new int[n+1];

			t[0] = -1, p[0] = -1;
			int c = 1;
			for (int i = 0; i < n; i++) {
				while (c > 0 && t[c-1] >= heights[i]) c--;
				l[i] = p[c-1] + 1;
				t[c] = heights[i];
				p[c++] = i;
			}

			p[0] = n, c = 1;
			for (int i = n-1; i >= 0; i--) {
				while (c > 0 && t[c-1] >= heights[i]) c--;
				r[i] = p[c-1] - 1;
				t[c] = heights[i];
				p[c++] = i;
			}

			int ans = 0;
			for (int i = 0; i < n; i++)
				ans = max(ans, (r[i] - l[i] + 1) * heights[i]);

			delete[] l;
			delete[] r;
			delete[] t;
			delete[] p;

			return ans;
		}

		int maximalRectangle(vector<vector<char>>& matrix) {
			if (matrix.size() == 0 || matrix[0].size() == 0) return 0;

			int m = matrix.size(), n = matrix[0].size();
			vector<vector<int>> gph;

			int ans = 0;
			for (int i = 0; i < m; i++) {
				vector<int> g;
				for (int j = 0; j < n; j++) {
					int k = (i == 0 ? 0 : gph[i-1][j]);
					int c = (matrix[i][j] == '1' ? k + 1 : 0);
					g.push_back(c);
				}
				ans = max(ans, largestRectangleArea(g));
				gph.push_back(g);
			}
			return ans;
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值