题目链接:https://leetcode.com/problems/maximal-rectangle/description/

题目大意:给出一个二维矩阵,计算最大的矩形面积(矩形由1组成)。例子如下:

85.Maximal Rectangle---dp

法一:将每一行的数据都看成是一个直方图,而每个直方图的高度都是由上一行得到的,例如,上述例子中,从上到下直方图的高度依次是:[1,0,1,0,0],[2,0,2,1,1],[3,1,3,2,2],[4,0,0,3,0]。也就是当当前值是0时,则高度是0;当前值是1时,则高度=上一行的高度+1。这样,对于每一行的直方图可以利用84题的求解办法,这里多的步骤就是将每一行数据转换成直方图,然后再根据每个直方图求解最大矩形面积。代码如下(耗时49ms):

 1     public int maximalRectangle(char[][] matrix) {
 2         if(matrix.length == 0) {
 3             return 0;
 4         }
 5         Stack<Integer> s = new Stack<Integer>();
 6         int h[] = new int[matrix[0].length];
 7         int res = 0;
 8         for(int i = 0; i < matrix.length; i++) {
 9             for(int j = 0; j < matrix[0].length; j++) {
10                 //转换成直方图
11                 h[j] = (matrix[i][j] == '1') ? (h[j] + 1) : 0;
12                 //根据每个直方图,计算其最大矩形面积,利用84题的方法
13                 while(!s.isEmpty() && h[s.peek()] >= h[j]) {
14                     int cur = s.pop();
15                     res = Math.max(res, h[cur] * (s.isEmpty() ? j : (j - s.peek() - 1)));
16                 }
17                 s.push(j);
18             }
19             while(!s.isEmpty()) {
20                 int cur = s.pop();
21                 res = Math.max(res, h[cur] * (s.isEmpty() ? h.length : (h.length - s.peek() - 1)));
22             }
23         }
24         return res;
25     }
View Code

相关文章:

  • 2021-08-15
  • 2021-09-15
  • 2022-03-02
  • 2021-12-03
  • 2021-08-18
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-03-08
  • 2021-06-13
相关资源
相似解决方案