LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

leetcode的题目真是越来越经典了。比如这个题目,就是一道男默女泪的题。
一般人拿到这个题目,除非做过类似的,很难一眼找出一个方法来,更别说找一个比较优化的方法了。
首先一个难点就是,你怎么判断某个区域就是一个矩形呢?
其次,以何种方式来遍历这个2D的matrix呢?
一般来说,对这种“棋盘式”的题目,像什么Queen啦,象棋啦,数独啦,如果没有比较明显的遍历方式,可以采用一行一行地遍历。(好像废话哦。。。)
然后,当遍历到(i, j)的时候,该做什么样的事情呢?想想,嗯,那我可不可以简单看看,以(i,j)为矩形左上角,能不能形成一个矩形,能不能形成多个矩形?那形成的矩形中,我们能不能找一个最大的呢?(有同学问,为毛你要以这个点为左上角,不为左下角,或者其他脚哩?因为我们打算从左到右,从上到下一行一行遍历嘛,这样就不会漏掉,说不定还能做一些优化)
首先,如果(i, j)是0,那肯定没法是矩形了。
如果是1,那么我们怎么找以它为左上角的矩形呢?呼唤画面感!

。。。你TM在逗我?==b
图中圈圈表示左上角的1,那么矩形的可能性是。。。太多啦,怎么数嘛!
我们可以试探地从左上角的1所在的列开始,往下数数,然后呢,比如在第一行,例如是蓝色的那个矩形,我们看看在列上,它延伸了多远,这个面积是可以算出来的。
然后继续,第二行,例如是那个红色的矩形,再看它延伸到多远,哦,我们知道,比第一行近一些,我们也可以用当前离第一行的行数,乘以延伸的距离,得到当前行表示的矩形面积。
但是到了第一个虚线的地方,它远远超过了上面的其他所有行延伸的距离了,注意它的上方都是空心的哦,所以,我们遇到这种情况,计算当前行和左上角1围成的面积的时候,只能取所有前面最小的延伸距离乘以当前离第一行的行数。其实,这对所有情况都是这样的,是吧?于是,我们不是就有方法遍历这些所有的矩形了嘛。
代码如下:
/**
* 以给出的坐标作为左上角,计算其中的最大矩形面积
* @param matrix
* @param row 给出坐标的行
* @param col 给出坐标的列
* @return 返回最大矩形的面积
*/
private int maxRectangle(char[][] matrix, int row, int col) {
int minWidth = Integer.MAX_VALUE;
int maxArea = 0;
for (int i = row; i < matrix.length && matrix[i][col] == '1'; i++) {
int width = 0;
while (col + width < matrix[row].length
&& matrix[i][col + width] == '1') {
width++;
}
if (width < minWidth) {// 如果当前宽度小于了以前的最小宽度,更新它,为下面的矩形计算做准备
minWidth = width;
}
int area = minWidth * (i - row + 1);
if (area > maxArea)
maxArea = area;
}
return maxArea;
}
maxRectangle
这样,我们再对每个点都调用一下上面的这个方法,不是就能求出最大面积了么。
解法一:
public int maximalRectangle(char[][] matrix) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int m = matrix.length;
        int n = m == 0 ? 0 : matrix[0].length;
        int maxArea = 0;
        for(int i = 0; i < m; i++){//row
            for(int j = 0; j < n; j++){//col
                if(matrix[i][j] == '1'){
                    int area = maxRectangle(matrix, i, j);
                    if(area > maxArea) maxArea = area;
                }
            }
        }
        return maxArea;
     }
这个需要O(n3),所以没有通过大集合的测试。
leetcode的讨论组给出了一个比较难理解的方法,这里就不采用了。
说说第三个方法。前一个笔记,我们讨论了柱状图的最大矩形面积,那可以O(n)的,学以致用呀!btw,leetcode的这两题也是挨一块儿的,用心良苦。。。。

如果我们把每一行看成x坐标,那高度就是从那一行开始往上数的1的个数。带入我们的maxAreaInHist方法,在O(n2)时间内就可以求出每一行形成的“柱状图”的最大矩形面积了。它们之中最大的,就是我们要的答案。
代码如下:
 public int maximalRectangle2(char[][] matrix) {
         int m = matrix.length;
         int n = m == 0 ? 0 : matrix[0].length;
         int[][] height = new int[m][n + 1];
         //actually we know that height can just be a int[n+1],
         //however, in that case, we have to write the 2 parts together in row traverse,
         //which, leetcode just doesn't make you pass big set
         //所以啊,leetcode是喜欢分开写循环的,即使时间复杂度一样,即使可以节约空间
         int maxArea = 0;
         for(int i = 0; i < m; i++){
             for(int j = 0; j < n; j++) {
                 if(matrix[i][j] == '0'){
                     height[i][j] = 0;
                 }else {
                     height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
                 }
             }
         }
         for(int i = 0; i < m; i++){
             int area = maxAreaInHist(height[i]);
             if(area > maxArea){
                 maxArea = area;
             }
         }
         return maxArea;
      }
      private int maxAreaInHist(int[] height){
          Stack<Integer> stack = new Stack<Integer>();
          int i = 0;
          int maxArea = 0;
          while(i < height.length){
              if(stack.isEmpty() || height[stack.peek()] <= height[i]){
                  stack.push(i++);
              }else {
                  int t = stack.pop();
                  maxArea = Math.max(maxArea, height[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
              }
          }
          return maxArea;
      }
这里有一个和leetcode相关的细节。就是本来在计算height数组的时候,我们没有必要分配成代码中的那个样子,一维就可以了,然后在遍历每一行的时候计算当前行的height数组,然后再计算maxArea。这种情况下还是过不了大集合,所以不得不为每一行都保存一个height,先期计算该二维数组。
总结:
1. 学到的新知识要用;
2. 画面感和逻辑分析都很重要,不可偏非。
LeetCode 笔记系列 18 Maximal Rectangle [学以致用]的更多相关文章
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
		题目: Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar he ... 
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
		题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ... 
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
		题目: Given an array of non-negative integers, you are initially positioned at the first index of the ... 
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
		题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ... 
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
		题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ... 
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
		题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ... 
- LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]
		题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Fol ... 
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
		题目:Given n non-negative integers representing an elevation map where the width of each bar is 1, com ... 
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
		题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ... 
随机推荐
- Mysql 的位运算符详解,mysql的优先级
			位运算是将给定的操作数转化为二进制后,对各个操作数每一位都进行指定的逻辑运算,得到的二进制结果转换为十进制数后就是位运算的结果.MySQL 5.0 支持6 种位运算符,如表4-4 所示. 可以发现,位 ... 
- unity, editorWindow update计时
			对于editorWindow,Time.deltaTime不起作用,所以需用下面方法对update进行计时: public class myEditorWindow : EditorWindow{ p ... 
- 如何隐藏你的 Linux 的命令行历史
			如果你是 Linux 命令行的用户,有的时候你可能不希望某些命令记录在你的命令行历史中.原因可能很多,例如,你在公司担任某个职位,你有一些不希望被其它人滥用的特权.亦或者有些特别重要的命令,你不希望在 ... 
- line: 1: Syntax error: word unexpected (expecting ")")
			开发板上运行可执行程序报出错误: line1: 1: Syntax error: word unexpected (expecting ")") 解决思路: 1.编译器的问题 用a ... 
- Spring Oauth2 with JWT Sample
			https://www.javacodegeeks.com/2016/04/spring-oauth2-jwt-sample.html ******************************** ... 
- [C++]在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include StdAfx.h”
			问题现象:在写好的.cpp文件后,编译报错.提示"你建立的工程使用了预编译功能, cpp最前边要留一行这样的内容:#include "StdAfx.h"问题原因:网上说是 ... 
- C语言  ·  Sine之舞
			基础练习 Sine之舞 时间限制:1.0s 内存限制:512.0MB 问题描述 最近FJ为他的奶牛们开设了数学分析课,FJ知道若要学好这门课,必须有一个好的三角函数基本功.所以他准备和奶 ... 
- ptxdist for sama5d3
			http://www.vahanus.net/~csc/scm/ptxdist-at91sama5d3-xpld.git/ 
- Web app root system property already set to different value 错误原因及解决
			http://yzxqml.iteye.com/blog/1761540 ——————————————————————————————————————————————————————————————— ... 
- ffmpeg 从内存中读取数据 .
			http://blog.csdn.net/leixiaohua1020/article/details/12980423 ——————————————————————————————————————— ... 
