Maximal Rectangle 最大的矩形面积
来源:互联网 发布:儿童剪刀车的危害知乎 编辑:程序博客网 时间:2024/05/15 00:36
有一个两维的矩阵,里面的值是 '0' 和 '1',找到面积最大的里面的值都是'1'的矩阵。
11010001101110011111011111011001101假设我们的矩阵长这样。如何能找到面积最大的都是1的呢?
记得以前的最大面积的直方图吗?不熟悉这个问题的请先看我的之前的post。(只要会求最大面积的直方图,这个问题就会很简单了)
我们可以将这个矩阵转化成直方图的想法来。
对于矩阵的第一行,对应的直方图为:
1101000
对于矩阵的第二行,对应的直方图为:
2202110所以,最终我们会有matrix.length个直方图,取最大的那个面积就是,最大的都是1的矩形面积了。
代码:
public int maximalRectangle(char[][] matrix) { int maxArea = 0; int m = matrix.length; if (m == 0) { return 0; } int n = matrix[0].length; int[] heights = new int[n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { heights[j] = (matrix[i][j] == '0' ? 0 : heights[j] + 1); } maxArea = Math.max(maxArea, largestRectangleAreaStack(heights)); } return maxArea; }
求最大直方图的代码:
public int largestRectangleAreaStack(int[] heights) { int i = 0; int maxArea = 0; int curArea = 0; Stack<Integer> store = new Stack<>(); // to store the left smaller index while (i < heights.length) { if (store.empty() || heights[store.peek()] <= heights[i]) { store.add(i); i++; } else { int curTop = store.pop(); // the ‘left smaller index’ is previous (previous to tp) item in stack and ‘right smaller index’ is ‘i’ (current index). if (!store.isEmpty()) { curArea = heights[curTop] * (i - store.peek() - 1); } else { curArea = heights[curTop] * i; } maxArea = Math.max(maxArea, curArea); } } while (!store.isEmpty()) { int curTop = store.pop(); if (!store.isEmpty()) { curArea = heights[curTop] * (i - store.peek() - 1); } else { curArea = heights[curTop] * i; } maxArea = Math.max(maxArea, curArea); } return maxArea; }
1 0
- Maximal Rectangle 最大的矩形面积
- Maximal Rectangle 最大的矩形
- 求全是1的最大矩阵面积 Maximal Rectangle @LeetCode
- LeetCode OJ 之 Maximal Rectangle (最大的矩形)
- Maximal Rectangle 二维矩形中最大的1个数
- LeetCode OJ 之 Maximal Rectangle (最大的矩形)
- LeetCode 85. Maximal Rectangle(最大矩形)
- [LeetCode]Maximal Rectangle寻找最大矩形
- 85 Maximal Rectangle (最大矩形)
- Largest Rectangle in Histogram 直方图中最大的矩形面积
- Largest Rectangle in Histogram 一排矩形中的最大的面积
- 【直方图面积】Maximal Rectangle
- 面积最大的矩形
- 面积最大的矩形
- 面积最大的矩形
- [LeetCode] 01矩阵中最大矩形 Maximal Rectangle
- Leetcode 85. Maximal Rectangle 最大矩形 解题报告
- LeetCode 85 Maximal Rectangle (最大子矩形 单调栈)
- leetcode 之reverse string ,Nim game, add digits
- 安装mplayer
- 设计模式---Iterator模式
- Swift 项目首次启动轮播页的制作
- 命令行模式下编译多个C/C++源文件
- Maximal Rectangle 最大的矩形面积
- 文件对话框
- zigbee协议栈应用(五)协议栈与温湿度传感器DHT11
- jsp运行原理和九大隐式对象
- acitvity生命周期
- 汇编指令:CLD STD MOVS LODS STOS
- Validate Binary Search Tree
- XSS绕过技术
- Java设计模式之观察者模式