Leetcode: Maximal Rectangle
来源:互联网 发布:淘宝格子铺登陆网址 编辑:程序博客网 时间:2024/06/16 00:55
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的进阶篇,计算柱状图最大矩形的解法可以进一步优化 - 不用两元组堆栈,用一个索引堆栈即可。关键是找到左右两侧比当前处理元素小的索引,面积为当前元素高度和左右索引差值的乘积。其他的就水到渠成了,把矩阵的每一行之上的所有元素看做一个柱状图。
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { int max_rect = 0; int rows = matrix.size(); if (rows == 0) { return max_rect; } int cols = matrix[0].size(); vector<int> sum(cols, 0); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (matrix[i][j] == '0') { sum[j] = 0; } else { ++sum[j]; } } max_rect = max(max_rect, largestRectangleArea(sum)); } return max_rect; } int largestRectangleArea(vector<int> &height) { int max_area = 0; stack<int> indices; int top_index, area; int i = 0; while (i < height.size()) { if (indices.empty() || height[indices.top()] <= height[i]) { indices.push(i++); } else { top_index = indices.top(); indices.pop(); area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1); max_area = max(max_area, area); } } while (!indices.empty()) { top_index = indices.top(); indices.pop(); area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1); max_area = max(max_area, area); } return max_area; }};
0 0
- 【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)
- iOS 开发小技巧
- Oracle数据库表空间查询
- STUN和TURN技术浅析
- 汇编串操作指令std 和 cld
- 程序员面试题精选100题(16)-O(logn)求Fibonacci数列[算法]
- Leetcode: Maximal Rectangle
- 程序开发感想
- STL之vector
- 数据结构上机测试4.1:二叉树的遍历与应用1
- linux-------定时备份文件
- Hibernate的flush机制深入
- 【Hadoop技术博客推荐】Hive的那些事
- 小明的花费预算
- POJ 1248 Safecracker