Maximal Rectangle
来源:互联网 发布:json jar包 编辑:程序博客网 时间:2024/06/05 10:40
两种方法,第一种参考 http://blog.csdn.net/fightforyourdream/article/details/17711893
Time O(n^3), Space O(n^2)
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { int rows = matrix.size(); if(rows == 0) return 0; int cols = matrix[0].size(); vector<vector<int> > ones(rows, vector<int>(cols, 0)); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { if(matrix[i][j] == '1') { if(j == 0) ones[i][j] = 1; else ones[i][j] = ones[i][j-1]+1; } } } int max_area = 0; for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { if(ones[i][j] != 0) { int minWidth = ones[i][j]; int idx = i; while(idx >= 0) { minWidth = min(minWidth, ones[idx][j]); int area = minWidth * (i-idx+1); max_area = max(max_area, area); idx--; } } } } return max_area; }};
第二种,利用了Largest Rectangle in Histogram的答案。逐行求解。Time O(n^2), Space O(n)。
http://www.cnblogs.com/lichen782/p/leetcode_maximal_rectangle.html
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { int rows = matrix.size(); if(rows == 0) return 0; int cols = matrix[0].size(); vector<int> heights(cols, 0); int result = 0; for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { if(matrix[i][j] == '1') heights[j]++; else heights[j] = 0; } int res = largestRectangleArea(heights); result = max(result, res); } return result; } int largestRectangleArea(vector<int> &height) { const int n = height.size(); if(n == 0) return 0; int max_area = 0; int area_top = 0; int idx = 0; stack<int> hists; while(idx < n) { if(hists.empty() || height[idx] >= height[hists.top()]) hists.push(idx++); else { int top = hists.top(); hists.pop(); int area_top = height[top]*(hists.empty()?idx:(idx-hists.top()-1)); max_area = std::max(max_area, area_top); } } while(!hists.empty()) { int top = hists.top(); hists.pop(); int area_top = height[top]*(hists.empty()?idx:(idx-hists.top()-1)); max_area = std::max(max_area, area_top); } return max_area; }};
0 0
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- Maximal Rectangle
- 平面设计师
- opencv学习步骤
- MQTT 折腾笔记----协议简读
- Java线程池使用说明
- java web学习笔记第一章
- Maximal Rectangle
- 将某一位置为一,将某一位不置为一,判断某一位是否为一
- Hibernate初次架设
- 深入理解const char*p,char const*p,char *const p,const char **p,char const**p,char *const*p,char**const
- MVC是什么?MVC与WebForm模式优缺点 | 及MVC里文件夹的功用
- 使用eclipse打开已有工程
- Xcode插件开发入门 —— JTTMagicLine
- HDU 2196 Computer | 树形dp
- CoInitializeEx failed ?