Leetcode 85. Maximal Rectangle 最大矩形 解題報告
阿新 • • 發佈:2019-01-22
1 解題思想
這道題我是轉化成上一道題來做的,對於每一行,看成給一個直方圖
2 原題
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
Subscribe to see which companies asked this question
3 AC解
public class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<Integer>();
int max_area=0,currentHeight,lastIndex,len;
for(int i=0;i<heights.length;i++){
currentHeight=heights[i];
//保持升序
if(stack.isEmpty() || heights[stack.peek()]<=currentHeight){
stack.push(i);
continue ;
}
//到了這裡,就是不滿足升序,需要彈出,注意當前len的判斷方式
while(stack.isEmpty()==false && heights[stack.peek()]>currentHeight){
lastIndex=stack.pop();
len=stack.isEmpty()?i:(i-stack.peek()-1);
max_area=Math.max(max_area,len*heights[lastIndex]);
}
stack .push(i);
}
//最後需要多處理一次
while(stack.isEmpty()==false){
lastIndex=stack.pop();
len=stack.isEmpty()?heights.length:(heights.length-stack.peek()-1);
max_area=Math.max(max_area,len*heights[lastIndex]);
}
return max_area;
}
//將問題變為條上一題
public int maximalRectangle(char[][] matrix) {
int n=matrix.length;
int max=0;
if(n<1) return 0;
int m=matrix[0].length;
if(m<1) return 0;
for(int i=0;i<n;i++){
int heights[]=new int[m];
for(int j=0;j<m;j++){
int t=i;
while(t>=0 && matrix[t--][j]=='1') heights[j]++;
}
max=Math.max(largestRectangleArea(heights),max);
}
return max;
}
}