Leetcode 85. Maximal Rectangle
来源:互联网 发布:in java.library.path 编辑:程序博客网 时间:2024/06/15 21:49
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 6.
public int maximalRectangle(char[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return 0; int row = matrix.length; int col = matrix[0].length; int max = 0; int[] height = new int[col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1; } max = Math.max(max, maxArea(height)); } return max; } private int maxArea(int[] heights) { int res = 0; Stack<Integer> s = new Stack<>(); int len = heights.length; for (int i = 0; i <= len; i++) { int h = (i == len ? 0 : heights[i]); if (s.isEmpty() || h >= heights[s.peek()]) s.push(i); else { int temp = s.pop(); res = Math.max(res, heights[temp] * (s.isEmpty() ? i : i - 1 - s.peek())); i--; } } return res; }
public int maximalRectangle(char[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return 0; int row = matrix.length; int col = matrix[0].length; int max = 0; int[] height = new int[col]; int[] left = new int[col]; int[] right = new int[col]; Arrays.fill(right, col); for (int i = 0; i < row; i++) { int cur_left = 0, cur_right = col; // height for (int j = 0; j < col; j++) { height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0; } for (int j = 0; j < col; j++) { left[j] = matrix[i][j] == '1' ? Math.max(left[j], cur_left) : 0; cur_left = matrix[i][j] == '1' ? cur_left : j + 1; } for(int j = col - 1; j >= 0; --j) { right[j] = matrix[i][j] == '1' ? Math.min(right[j], cur_right) : col; cur_right = matrix[i][j] == '1' ? cur_right : j; } for(int j = 0; j < col; ++ j) { max = Math.max(max, (right[j] - left[j]) * height[j]); } } return max;
阅读全文
0 0
- LeetCode 85. Maximal Rectangle
- [Leetcode] 85. Maximal Rectangle
- LeetCode --- 85. Maximal Rectangle
- [LeetCode]*85.Maximal Rectangle
- [leetcode] 85.Maximal Rectangle
- Leetcode 85. Maximal Rectangle
- leetcode 85. Maximal Rectangle
- LeetCode 85. Maximal Rectangle
- Leetcode 85. Maximal Rectangle
- Leetcode:85. Maximal Rectangle
- LeetCode 85. Maximal Rectangle
- LeetCode-85.Maximal Rectangle
- leetcode.85. Maximal Rectangle
- leetcode 85. Maximal Rectangle
- Leetcode 85. Maximal Rectangle
- [LeetCode] 85. Maximal Rectangle
- leetcode 85.Maximal Rectangle
- leetcode:85. Maximal Rectangle
- 在 linux 下使用 CMake 构建应用程序
- java判断字符串是否是日期类型
- 用js实现输入年月日输出这一天是这一年的第几天
- SLF4J和log4j的使用
- windows 如何用命令查看文件目录
- Leetcode 85. Maximal Rectangle
- 新的起点
- 保护共享数据
- GDB十分钟教程
- 2017.6.22
- MyBatis中#{}和${}的区别详解
- 作业6.22
- ActiveMQ
- 在Archives之后出现Other Items