leetcode85. 最大矩形
【摘要】 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] 输出: 6 ...
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
和leetcode84没什么区别,就是一行一行更新出“高度”,一行一行的跑一遍单调栈即可。
-
class Solution {
-
public int leetcode84(int[] heights) {
-
Stack < Integer > stack = new Stack < > ();
-
stack.push(-1);
-
int maxarea = 0;
-
for (int i = 0; i < heights.length; ++i) {
-
while (stack.peek() != -1 && heights[stack.peek()] >= heights[i])
-
maxarea = Math.max(maxarea, heights[stack.pop()] * (i - stack.peek() - 1));
-
stack.push(i);
-
}
-
while (stack.peek() != -1)
-
maxarea = Math.max(maxarea, heights[stack.pop()] * (heights.length - stack.peek() -1));
-
return maxarea;
-
}
-
-
public int maximalRectangle(char[][] matrix) {
-
-
if (matrix.length == 0) return 0;
-
int maxarea = 0;
-
int[] dp = new int[matrix[0].length];
-
-
for(int i = 0; i < matrix.length; i++) {
-
for(int j = 0; j < matrix[0].length; j++) {
-
dp[j] = matrix[i][j] == '1' ? dp[j] + 1 : 0;
-
}
-
maxarea = Math.max(maxarea, leetcode84(dp));
-
} return maxarea;
-
}
-
}
文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。
原文链接:fantianzuo.blog.csdn.net/article/details/104027791
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)