题目描述

原题链接

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例 1:
image.png

  1. 输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
  2. 输出:6
  3. 解释:最大矩形如上图所示。

示例 2:

  1. 输入:matrix = []
  2. 输出:0

示例 3:

  1. 输入:matrix = [["0"]]
  2. 输出:0

示例 4:

  1. 输入:matrix = [["1"]]
  2. 输出:1

示例 5:

  1. 输入:matrix = [["0","0"]]
  2. 输出:0

提示:

  • rows == matrix.length

cols == matrix[0].length
1 <= row, cols <= 200
matrix[i][j] 为 ‘0’ 或 ‘1’

个人解法

Java

JavaScript

更优解法

Java

暴力解法

1F853D642338F7EA7DA543704B3965CE.jpg

  1. class Solution {
  2. public int maximalRectangle(char[][] matrix) {
  3. int m=matrix.length,n=matrix[0].length;
  4. if (m == 0) {
  5. return 0;
  6. }
  7. //用于记录每个点为右下角时,左边最大连续1的数量(包括自己)
  8. int[][] left=new int[m][n];
  9. for (int i=0;i<m;i++){
  10. for (int j=0;j<n;j++){
  11. if (matrix[i][j]=='1'){
  12. left[i][j]=(j==0 ? 0: left[i][j-1])+1;
  13. }
  14. }
  15. }
  16. int ressult=0;
  17. for (int i=0;i<m;i++){
  18. for (int j=0;j<n;j++){
  19. if (matrix[i][j]=='0'){
  20. continue;
  21. }
  22. //初始矩形宽度
  23. int width=left[i][j];
  24. //初始面积,为右下角时,最小的面积也有这么大
  25. int area =width;
  26. for (int k=i-1;k>=0;k--){
  27. width=Math.min(width,left[k][j]);
  28. area=Math.max(area,(i-k+1)*width);
  29. }
  30. ressult=Math.max(ressult,area);
  31. }
  32. }
  33. return ressult;
  34. }
  35. }

单调栈

image.png
image.png

  1. class Solution {
  2. public int largestRectangleArea(int[] heights) {
  3. int len = heights.length;
  4. int[] left = new int[len];
  5. int[] right = new int[len];
  6. Stack<Integer> stack = new Stack<>();
  7. stack.push(-1);
  8. for (int i = 0; i < len; i++) {
  9. while (stack.peek() != -1 && heights[i] <= heights[stack.peek()]) {
  10. stack.pop();
  11. }
  12. left[i] = stack.peek();
  13. stack.push(i);
  14. }
  15. stack = new Stack<>();
  16. stack.push(-1);
  17. for (int i = len-1; i >=0; i--) {
  18. while (stack.peek() != -1 && heights[i] <= heights[stack.peek()]) {
  19. stack.pop();
  20. }
  21. if (stack.peek()==-1){
  22. right[i]=len;
  23. }else {
  24. right[i] = stack.peek();
  25. }
  26. stack.push(i);
  27. }
  28. int max=-1;
  29. for (int i=0;i<len;i++){
  30. max=Math.max(max,(right[i]-left[i]-1)*heights[i]);
  31. }
  32. return max;
  33. }
  34. public int maximalRectangle(char[][] matrix) {
  35. int m=matrix.length,n=matrix[0].length;
  36. if (m == 0) {
  37. return 0;
  38. }
  39. int[] height=new int[n];
  40. int ressult=0;
  41. for (int i=0;i<m;i++){
  42. for (int j=0;j<n;j++){
  43. if (matrix[i][j]=='1'){
  44. height[j]+=1;
  45. }else {
  46. height[j]=0;
  47. }
  48. }
  49. ressult=Math.max(ressult,largestRectangleArea(height));
  50. }
  51. return ressult;
  52. }
  53. }

JavaScript