diff --git a/README.md b/README.md index 55e832a..893d196 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 82 |[Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/82.%20Remove%20Duplicates%20from%20Sorted%20List%20II.md)|Medium| | | 83 |[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/83.%20Remove%20Duplicates%20from%20Sorted%20List.md)|Easy| | | 84 |[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)|[C++](solutions/84.%20Largest%20Rectangle%20in%20Histogram.md)|Hard| | +| 85 |[Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)|[C++](solutions/85.%20Maximal%20Rectangle.md)|Hard| | | 86 |[Partition List](https://leetcode.com/problems/partition-list/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/86.%20Partition%20List.md)|Medium| | | 88 |[Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/88.%20Merge%20Sorted%20Array.md)|Easy| | | 89 |[Gray Code](https://leetcode.com/problems/gray-code/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/89.%20Gray%20Code.md)|Medium| | diff --git a/solutions/85. Maximal Rectangle.md b/solutions/85. Maximal Rectangle.md new file mode 100644 index 0000000..53e1510 --- /dev/null +++ b/solutions/85. Maximal Rectangle.md @@ -0,0 +1,122 @@ +# [85. Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) + +# 思路 + +## 思路一 + +对于二维矩阵的第 i 行,这一行及上面的部分可以看成是一个直方图,而在直方图里求最大矩形即[84. Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/),我们可以用单调栈在线性复杂度内求解84题,详见[84题解](84.%20Largest%20Rectangle%20in%20Histogram.md)。 + +所以对于此题,我们只需要开辟一个表示直方图的一维数组`heights`,然后对于每一行,建立直方图,然后再用84题思路(代码中采用的是[84题解思路二](84.%20Largest%20Rectangle%20in%20Histogram.md))进行求解。我们可以根据上一行的直方图`heights`在线性时间复杂度内建立当前行的直方图`heights`: +* 如果`matrix[i][j] == '0'`,则`heights[j] = 0`; +* 否则,`heights[j] += 1`; + +时间复杂度O(MN),空间复杂度O(N);其中M和N分别为高和宽。 + +## 思路二 + +对于每个点,我们会通过以下步骤计算出一个矩形: + +* 不断向上方遍历,直到遇到“0”,以此找到矩形的高度。 +* 向左右两边扩展,直到无法容纳这个高度。 + +例如,找到黄色点对应的矩形([图片来源](https://leetcode-cn.com/problems/maximal-rectangle/solution/zui-da-ju-xing-by-leetcode/)): + +