【LeetCode】85. Maximal Rectangle
2024-08-26 14:58:09
Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
如果用DP来做,判断(begin1,end1)~(begin2,end2)范围是否全1,会超时。
对于矩阵matrix,逐行构建height数组,调用Largest Rectangle in Histogram即可。
对matrix第i行构建height数组方法:对于height[j],即从matrix[i][j]开始,最多到达matrix[0][j]的连续1个数。
class Solution {
public: int maximalRectangle(vector<vector<char> > &matrix) {
int ret = ;;
if(matrix.empty() || matrix[].empty())
return ret;
int m = matrix.size();
int n = matrix[].size();
for(int i = ; i < matrix.size(); i ++)
{
vector<int> height(n, );
for(int j = ; j < n; j ++)
{
int r = i;
while(r >= && matrix[r][j] == '')
{
height[j] ++;
r --;
}
}
ret = max(ret, largestRectangleArea(height));
}
return ret;
} int largestRectangleArea(vector<int> &height) {
if(height.empty())
return ; int result = ;
stack<int> s; //elements in stack s are kept in ascending order
int ind = ;
while(ind < height.size())
{
if(s.empty() || height[ind]>=s.top())
{
s.push(height[ind]);
}
else
{
int count = ; //pop count
while(!s.empty() && height[ind]<s.top())
{
int top = s.top();
s.pop();
count ++;
result = max(result, count*top);
}
for(int i = ; i <= count; i ++)
s.push(height[ind]); //push count+1 times
}
ind ++;
}
//all elements are in stack s, and in ascending order
int count = ;
while(!s.empty())
{
count ++;
int top = s.top();
s.pop();
result = max(result, count*top);
} return result;
}
};
最新文章
- Xamarin.Forms.Platform.Perspex, Xamarin Forms 的 Perspex(号称下一代WPF) 实现
- ubuntu qq
- [ios][swift]swift GPS传感器的调用
- 使用OmniGraffle制作原型图
- C# 打印异常
- Oracle PL/SQL 找出100以内是3和5的倍数的数 循环语句
- Emmet(前身是zen coding)介绍和使用
- ViewPager.getChildCount() 含义
- Linux最佳的云存储服务分析
- vue的环境安装(一node环境)
- MySQL data sync to Oracle with OGG(Remote Delivery)
- 2.Swift快速浏览
- String[]与List<;String>;的相互转换
- ES6 Symbol的应用场景
- 【Python】TypeError: a bytes-like object is required, not &#39;str&#39;解决
- vector读入指定行数但不指定列数的数字
- 6个原则、50条秘技提高HTML5应用及网站性能
- 一段有用的javascript加密解密
- asp 支付宝 企业版 接口 支持网银接口 ,网银直接支付
- ASP.NET Core 2.2 基础知识(五) 环境
热门文章
- React Native中树 TreeView 实现(2)
- mysql内存参数整理和条调优以及内存统计
- eclipse.ini 文件使用说明
- ubuntu上安装systemtap
- GCC安装UBUNTU
- WebService如何抛出干净的异常
- 【提醒】使用 iptables 时,特别注意 规则的顺序
- Codeforces Round #261 (Div. 2)[ABCDE]
- linux下的springboot项目启动文件
- SQL VM上磁盘延迟高, 但Host和Storage Array上的延迟却很低的问题