您的位置:首页 > 职场人生

[LeetCode] Maximal Rectangle

2014-01-04 07:52 363 查看
问题:

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

分析:

参考Largest Rectangle in
Histogram这道题以及这篇文章。我们面对的这道题可以转化为柱形图,然后用前面这道题来解决。需要注意的是,转换柱形图的时候,如果是从底到顶,那么一旦一根柱形图上遇到了一个0,则之前计算过的都不算了,之后要清零重新计算柱形高度。

代码:(O(mn))

class Solution {
public:
int maxArea(vector<int> heights) {
heights.push_back(0);
stack<int> s;
int result = 0;
int i = 0;
while (i < heights.size()) {
if (s.empty() || heights[s.top()] <= heights[i])
s.push(i++);
else {
int temp = s.top();
s.pop();
if(s.empty())
result = max(result, heights[temp] * i);
else
result = max(result, heights[temp] * (i - s.top() - 1));
}
}
return result;
}

int maximalRectangle(vector<vector<char> > &matrix) {
int m = matrix.size();
if (m == 0) return 0;
int n = matrix[0].size();
if (n == 0) return 0;
vector<vector<int> > heights (m, vector<int>(n, 0));
for (int i = 0; i < n; i ++) {
heights[m-1][i] = matrix[m-1][i] - '0';
}
for (int i = m-1; i >= 0; i --) {
for (int j = 0; j < n; j ++) {
if (matrix[i][j] == '1')
heights[i][j] = (i == m-1 ? 1 : heights[i+1][j] + 1);
}
}
int result = 0;
for (int i = m-1; i >=0; i --) {
int temp_result = maxArea(heights[i]);
result = max(temp_result, result);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 面试 leetcode