【leetcode】Maximal Rectangle (hard)★

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.

找到01矩形中最大的全1子矩阵。

我自己的思路:

我先用一个跟输入相同大小的矩阵numInCol 存储从当前位置开始向下有多少连续的1。

  如

1 0 1
0 1 1
1 1 1

其numInCol 是

1 0 3
0 2 2
1 1 1

然后用一个变量tmpans来记录以某个位置开始,其右下矩形的最大全1矩阵的大小。

方法是如果当前位置是1,则用1 * numInCol[当前位置]     即只有这一列的大小

如果其后面紧接着的位置也是1,则用 2 * (这两列中连续1高度小的值)  即这两列的矩形大小

如果其后面紧接着的位置也是1,则用 3 * (这三列中连续1高度小的值)  即这三列的矩形大小

........................

依次类推

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        if(matrix.empty())
            return 0;

        int row = matrix.size();
        int col = matrix[0].size();
        int ans = 0;

        vector<vector<int> > numInCol(row, vector<int>(col, 0));
        int tmpans = 0;

        //对每一列
        for(int j = 0; j < col; j++)
        {
            numInCol[row - 1][j] = (matrix[row - 1][j] == ‘1‘) ? 1 : 0;
            for(int i = row - 2; i >= 0; i--)
            {
                if(matrix[i][j] == ‘1‘)
                {
                    numInCol[i][j] = numInCol[i + 1][j] + 1;
                }
            }
        }

        //对整个矩阵
        for(int i = row - 1; i >= 0; i--)
        {
            tmpans = numInCol[i][col - 1];
            ans = max(ans, tmpans);
            for(int j = col - 2; j >= 0; j--)
            {
                int jj = j;
                int len = 1;
                int minlen = numInCol[i][j];
                while(jj < col && matrix[i][jj] == ‘1‘)
                {
                    minlen = min(minlen, numInCol[i][jj]);
                    tmpans = max(tmpans, len * minlen);
                    ans = max(ans, tmpans);
                    jj++;
                    len++;

                }
            }
        }

        return ans;
    }
};

int main()
{
    Solution s;
    vector<vector<char> > matrix(4, vector<char>(5, ‘0‘));
    matrix[0][1] = ‘1‘;
    matrix[0][2] = ‘1‘;
    matrix[0][3] = ‘1‘;
    matrix[1][1] = ‘1‘;
    matrix[1][2] = ‘1‘;
    matrix[2][1] = ‘1‘;
    matrix[2][2] = ‘1‘;
    matrix[2][3] = ‘1‘;

    int ans = s.maximalRectangle(matrix);

    return 0;
}

网上的答案,整体的思路差不多,也是通过一列列的数据来判断,但是并没有像我一样,把所有的值都存下来,而是只存了一行的列信息,每到新的一行再更新,这样空间少了很多。其次,没有像我这样每次都循环后面的列是否为1,而是利用栈,如果高度是递增的就先不计算最大矩形而是把信息压栈,等到遇到高度减少的时候再依次计算这一段的最大矩形。

class Solution {
public:
    int maximalRectangle(vector<vector<char>> &matrix) {
        if (matrix.empty()) return 0;
        int rows = matrix.size();
        int cols = matrix[0].size();
        int maxArea = 0;
        vector<int> heights(cols + 1, 0);
        vector<int> stack;
        for (int i = 0; i < rows; i++) {
            stack.clear();
            for (int j = 0; j < cols + 1; j++) {
                if (j < cols) {
                    if (matrix[i][j] == ‘1‘) {
                        heights[j]++;
                    } else {
                        heights[j] = 0;
                    }
                }
                if (stack.empty() || heights[j] >= heights[stack.back()]) {
                    stack.push_back(j);
                    continue;
                }
                while (!stack.empty() && heights[j] < heights[stack.back()]) {
                    int top = stack.back();
                    stack.pop_back();
                    int begin = stack.empty() ? 0 : stack.back() + 1;
                    int area = heights[top] * (j - begin);
                    if (area > maxArea) maxArea = area;
                }
                stack.push_back(j);
            }
        }
        return maxArea;
    }
};
时间: 2024-12-18 20:36:24

【leetcode】Maximal Rectangle (hard)★的相关文章

【leetcode】Maximal Rectangle

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. 使用dpHeight[]数组来记录到第i行为止,第j个位置垂直连续包含多少个1(包括matrxi[i][j]).如: 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 有如下结果: 第1行: dpHeight[] =

【leetcode】Largest Rectangle in Histogram

题目信息如下: 1.题目地址为:https://leetcode.com/problems/largest-rectangle-in-histogram/ 2.题目意思为: 给定一个非负数组height,代表了矩形的高度(其中矩形宽度为1),求在其中能找出最大的矩形面积. 3.给的例子为: height = [2,1,5,6,2,3]. 输出为:10.示意图如下 那么下面为正文,讲讲算法的依据(以上面的例子为例): 1.第一个2就没什么讲的了,面积必然为2. 2.当指针指向height[1]的时

【Leetcode】Maximal Square

题目链接:https://leetcode.com/problems/maximal-square/ 题目: Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area. For example, given the following matrix: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0

【LeetCode】223. Rectangle Area

题目: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. Assume that the total area is never beyond the maximum possible value of int

【LeetCode】223. Rectangle Area 解题小结

题目: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. Assume that the total area is never beyond the maximum possible value of int

【LeetCode】数组

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum [4]Median of Two Sorted Arrays [11]Container With Most Water [15]3Sum [16]3Sum Closest [18]4Sum [26]Remove Duplicates from Sorted Array [27]Remove Element [31]Next Permutatio

【LeetCode】栈 stack(共40题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [20]Valid Parentheses [42]Trapping Rain Water [71]Simplify Path [84]Largest Rectangle in Histogram [85]Maximal Rectangle [94]Binary Tree Inorder Traversal [103]Binary Tree Zigzag Level

【LeetCode】哈希表 hash_table(共88题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target . 题解:我这次最大范围的优化代码, hash-table + one pass,时间复杂度 O(N),空间复杂度 O(N).重点在于动态找,一边生成hash-tabl

【leetcode刷题笔记】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. 题解,很巧妙的一道题,对于一个0-1矩阵,它的每一行及以上都可以看作一个直方图(如下图所示),利用Largest Rectangle in Histogram的方法,可以在O(n)的时间搜索出这一行及以上的直方图中面积最大的矩形,对矩阵的每一行依次做这个操作,就可