LeetCode 85.Maximal Rectangle (DP-專題)
阿新 • • 發佈:2019-02-09
題目:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6Seen this question in a real interview before? YesNo
分析:
class Solution { public int maximalRectangle(char[][] matrix) { //給定矩陣座標,其中求出最大面積的表示 //採用分別記錄左右高可達邊界座標,從而面積值為(右-左)*gao if(matrix==null||matrix.length==0) return 0; int m=matrix.length,n=matrix[0].length; int [] right=new int[n]; int [] left=new int[n]; int [] height=new int[n]; int maxArea=0; //對於右邊界預設值為n Arrays.fill(right,n); for(int i=0;i<m;i++){ int curLeft=0; int curRight=n; //求高 for(int j=0;j<n;j++){ if(matrix[i][j]=='1'){ height[j]++; }else{ height[j]=0; } } //求左邊界 for(int j=0;j<n;j++){ if(matrix[i][j]=='1'){ left[j]=Math.max(left[j],curLeft); }else{ left[j]=0; curLeft=j+1; } } //求右邊界(從右邊開始) for(int j=n-1;j>=0;j--){ if(matrix[i][j]=='1'){ right[j]=Math.min(right[j],curRight); }else{ right[j]=n; curRight=j; } } //求面積 for(int j=0;j<n;j++){ maxArea=Math.max(maxArea,(right[j]-left[j])*height[j]); } } return maxArea; } }