leetcode:221. 最大正方形
题目
在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
示例:![[中等] 221. 最大正方形 - 图1](/uploads/projects/liangduo-rjrcs@ggu4wq/127231a56ac45fa553e05291ebec9d44.jpeg)
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]输出:4
![[中等] 221. 最大正方形 - 图2](/uploads/projects/liangduo-rjrcs@ggu4wq/5d3f09518f0943eed02e99e077fc6121.jpeg)
输入:matrix = [["0","1"],["1","0"]]输出:1
输入:matrix = [["0"]]输出:0
解答 & 代码
解法一:单调栈
思路同:
[困难] 85. 最大矩形
class Solution {public:int maximalSquare(vector<vector<char>>& matrix) {if(matrix.size() == 0 || matrix[0].size() == 0)return 0;int rows = matrix.size();int cols = matrix[0].size();vector<vector<int>> right1Len(rows, vector<int>(cols, 0));for(int i = 0; i < rows; ++i){right1Len[i][cols - 1] = matrix[i][cols - 1] == '0' ? 0 : 1;for(int j = cols - 2; j >= 0; --j)right1Len[i][j] = matrix[i][j] == '0' ? 0 : right1Len[i][j + 1] + 1;}int result = 0;for(int j = 0; j < cols; ++j){vector<int> up(rows);stack<int> s;for(int i = 0; i < rows; ++i){while(!s.empty() && right1Len[s.top()][j] >= right1Len[i][j])s.pop();up[i] = s.empty() ? -1 : s.top();s.push(i);}vector<int> down(rows);while(!s.empty())s.pop();for(int i = rows - 1; i >= 0; --i){while(!s.empty() && right1Len[s.top()][j] >= right1Len[i][j])s.pop();down[i] = s.empty() ? rows : s.top();s.push(i);}for(int i = 0; i < rows; ++i){int height = right1Len[i][j];int width = down[i] - up[i] - 1;int edge = min(height, width);int curArea = edge * edge;// cout << "i = " << i << ", j = " << j << ": height = " << height << ", down[i] = " << down[i] << ", up[i] = " << up[i] << ", curArea = " << curArea << endl;result = max(result, curArea);}}return result;}};
复杂度分析:设矩阵行数为 m,列数为 n
- 时间复杂度
:遍历矩阵中的一列,时间复杂度 O(n)。然后对每一列的每一个元素,用单调栈求其下方最近的比它小的位置,求其上方最近的比它小的位置,再分别以每个元素为高度求最大矩形面积,三个操作的时间复杂度都为 O(m)
- 空间复杂度 O(mn):
right1Len矩阵的空间复杂度
执行结果:
执行结果:通过执行用时:88 ms, 在所有 C++ 提交中击败了 10.02% 的用户内存消耗:22.2 MB, 在所有 C++ 提交中击败了 5.04% 的用户
