LeetCode: Maximal Rectangle
来源:互联网 发布:二战中国功劳排名 知乎 编辑:程序博客网 时间:2024/05/17 20:34
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
O(n^3)方法,348 milli secs
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int y = matrix.size(); if (y == 0) return 0; int x = matrix[0].size(); if (x == 0) return 0; vector< vector<int> > result(y, vector<int>(x)); for (int j = 0; j < y; ++j) { for (int i = 0; i < x; ++i) { result[j][i] = '0' == matrix[j][i] ? 0 : 1; } } for (int j = 0; j < y; ++j) { for (int i = 1; i < x; ++i) { result[j][i] += (0 == result[j][i] ? 0 : result[j][i-1]); } } int max = 0; for (int i = 0; i < x; ++i) { for (int j = 0; j < y; ++j) { int maxWidth = result[j][i]; for (int k = j; k < y; ++k) { maxWidth = maxWidth < result[k][i] ? maxWidth : result[k][i]; max = max > maxWidth*(k-j+1) ? max : maxWidth*(k-j+1); } } } return max; }};
O(n^2)方法: 44 milli secs
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int y = matrix.size(); if (y == 0) return 0; int x = matrix[0].size(); if (x == 0) return 0; vector< vector<int> > result(y, vector<int>(x)); for (int j = 0; j < y; ++j) { int tmp = 0; for (int i = 0; i < x; ++i) { if ('0' == matrix[j][i]) tmp = 0; else ++tmp; result[j][i] = tmp; } } int max = 0; int* l = new int[y]; int* r = new int[y]; for (int i = 0; i < x; ++i) { l[0] = 0; for (int j = 1; j < y; ++j) { int k = j; while(k > 0 && result[j][i] <= result[k-1][i]) k = l[k-1]; l[j] = k; } r[y-1] = y - 1; for(int j = y-2; j >= 0; --j) { int k = j; while(k < y - 1 && result[j][i] <= result[k+1][i]) k = r[k+1]; r[j] = k; } for (int j = 0; j < y; ++j) { int ar = (r[j] - l[j] + 1) * result[j][i]; max = max > ar ? max : ar; } } return max; }};
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- LeetCode: Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode: Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [leetcode] Maximal Rectangle
- [LeetCode]Maximal Rectangle
- [leetcode]Maximal Rectangle
- LeetCode-Maximal Rectangle
- [leetcode] Maximal Rectangle
- Leetcode Maximal Rectangle
- [LeetCode] Maximal Rectangle
- leetcode Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode | Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [Leetcode] Maximal Rectangle (Java)
- WordPress主题设计技巧:调用文章第一张图片方法
- 基于FPGA的LCD12864显示字符
- Fragment_学习3
- 10种提高WordPress访问速度的方法
- Class.forName() 和 ClassLoader.loadClass()的区别?
- LeetCode: Maximal Rectangle
- wp-config.php文件小功能分享
- BNU Playing Field
- 用Munin监控Linux服务器性能
- android LinearLayout类研究
- 国庆长假结束了
- oracle 存储过程的基本语法
- 关于Repeater控件的使用
- 【转载】fatal error C1010: unexpected end of file while looking for precompiled header directive