Leetcode Maximal Rectangle
2016-07-20 03:46
363 查看
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Difficulty: Hard
Solution: http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/
public class Solution {
public int helper(int[] height){
Stack<Integer> stack = new Stack<Integer>();
int i = 0, ans = 0;
while(i < height.length){
if(stack.isEmpty() || height[i] >= height[stack.peek()]){
stack.push(i);
i++;
}
else{
int temp = stack.pop();
ans = Math.max(ans, height[temp] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return ans;
}
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(m == 0) return 0;
int n = matrix[0].length;
int ans = 0;
int[][] nums = new int[m][n + 1];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && matrix[i][j] == '1'){
nums[i][j] = 1;
}
else if(matrix[i][j] == '1'){
nums[i][j] = 1 + nums[i-1][j];
}
}
}
for(int i = 0; i < m; i++){
ans = Math.max(ans, helper(nums[i]));
}
return ans;
}
}
Difficulty: Hard
Solution: http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/
public class Solution {
public int helper(int[] height){
Stack<Integer> stack = new Stack<Integer>();
int i = 0, ans = 0;
while(i < height.length){
if(stack.isEmpty() || height[i] >= height[stack.peek()]){
stack.push(i);
i++;
}
else{
int temp = stack.pop();
ans = Math.max(ans, height[temp] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return ans;
}
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(m == 0) return 0;
int n = matrix[0].length;
int ans = 0;
int[][] nums = new int[m][n + 1];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && matrix[i][j] == '1'){
nums[i][j] = 1;
}
else if(matrix[i][j] == '1'){
nums[i][j] = 1 + nums[i-1][j];
}
}
}
for(int i = 0; i < m; i++){
ans = Math.max(ans, helper(nums[i]));
}
return ans;
}
}
相关文章推荐
- IOS控件总是看不见。
- Leetcode Binary Tree Maximum Path Sum
- Leetcode Odd Even Linked List
- 重建控制文件后,各文件(datafile、control file、redo log)中scn的关系
- selenium 多线程
- Reorder List
- Leetcode Remove Duplicates from Sorted List
- Leetcode Path Sum
- Leetcode Power of Two/Three/Four
- Leetcode Rotate Image
- 最小边割集
- 云服务器上安装配置Filezilla Server的坑!
- 在安装Ubuntu的MacBook上更改Apple 键盘模式
- 算法日记(Java实现)第20160719(5)期——POJ1008
- 在MacBook Pro 12-1 with ubuntu 15.10 上安装风扇控制器(mbpfan)
- HDU5723 2016 Multi-University Training Contest 1 (最小生成树+dfs)
- 百度地图API 地理位置获取和大头针显示当前位置
- KVM的网络Networking-qemu-kvm和openvswitch原型环境部署和基本测试 (3)
- 创建虚拟机-qemu-kvm和openvswitch原型环境部署和基本测试 (2)
- 基于栈数据结构的算法(poj-布尔表达式)