这个也不是我自己做出来的,感觉我还打不到这个水平,我好菜!
class Solution: def maximalRectangle(self, matrix) -> int: if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) height = [0] * (col + 2) res = 0 for i in range(row): stack = [] for j in range(col + 2): if 1<=j<=col: if matrix[i][j-1] == "1": height[j] += 1 else: height[j] = 0 while stack and height[stack[-1]] > height[j]: cur = stack.pop() res = max(res, (j - stack[-1] - 1)* height[cur]) stack.append(j) return res
执行用时 :180 ms, 在所有 python 提交中击败了89.43%的用户
内存消耗 :19.5 MB, 在所有 python 提交中击败了6.25%的用户
——2019.11.4
时隔这么久,我自己依然写不出来。
之前看懂的也忘了,跟没看一样。。。
动态规划:
public int maximalRectangle(char[][] matrix) { if(matrix.length == 0){ return 0; } int m = matrix.length; int n = matrix[0].length; int[] left = new int[n]; int[] right = new int[n]; int[] height = new int[n]; //高度为什么是n Arrays.fill(right,n); int ret = 0; //记录面积 for(int i = 0;i<m;++i){ int curleft = 0,curright = n; for(int j = 0;j<n;++j){ if(matrix[i][j] == '1') { ++height[j]; left[j] = Math.max(left[j], curleft); }else{ curleft = j+1; height[j] = 0; left[j] = 0; } } for(int j = n-1;j>=0;--j){ if(matrix[i][j] =='1'){ right[j] = Math.min(right[j],curright); ret = Math.max(ret,height[j]*(right[j]-left[j])); }else{ right[j] = n; curright = j; } } } return ret; }
——2020.6.25 端午节