Leetcode 85. Maximal Rectangle
2016-04-10 21:10
225 查看
Question
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.Code
public int maximalRectangle(char[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return 0; } int rows = matrix.length; int cols = matrix[0].length; int[][] h = new int[rows][cols]; int max = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { h[i][j] = matrix[i][j] == '1' ? 1: 0; if (i != 0 && h[i][j] != 0) { h[i][j] = h[i - 1][j] + 1; } if (j == cols - 1) { max = Math.max(max, maxArea(h[i])); } } } return max; } public int maxArea(int[] h) { Stack<Integer> s = new Stack<Integer>(); int max = 0; int i = 0; // 注意,这里使用<= 因为当i到达最后,需要计算一次。 while (i <= h.length) { // if (s.isEmpty() || i < h.length && h[i] >= h[s.peek()]) { s.push(i); i++; } else { int height = h[s.pop()]; int width = s.isEmpty() ? i: i - s.peek() - 1; max = Math.max(max, height * width); } } return max; }
相关文章推荐
- 消息队列应用场景
- 148. Sort List
- Lua进阶
- jmeter XML格式的结果中各属性的含义
- margin(边界)、border(框边)、padding(填充)、content(填充)
- Nginx反向代理后端多个Tomcat、Nginx+PHP服务器(Nginx的代理和负载功能) 推荐
- 题目1153:括号匹配问题
- JSTL fmt 格式化日期时间
- 树状数组求第K小值 (spoj227 Ordering the Soldiers && hdu2852 KiKi's K-Number)
- 018.php函数
- 图片轮换特效
- 你真的会写单例模式吗
- 20145237《Java程序设计》实验报告一
- 用体元滤波器进行降低采样
- NYOJ284坦克大战
- Calculation PartⅡ
- 广东工业大学2016校赛决赛-网络赛 1169 Problem A: Krito的讨伐 优先队列
- HDU:4535 吉哥系列故事——礼尚往来(数学:错排)
- 017.php跳出循环break和continue
- RHEL7中控制服务的方法---systemd