zoukankan      html  css  js  c++  java
  • Leetcode#85 Maximal Rectangle

    原题地址

    这道题跟最大子矩阵的思想比较类似,都是降一维(减少变量数量)转化成简单问题

    指定任意一行作为矩形的下边界,那么问题就变成了求直方图的最大面积的矩形,参见之前的这篇文章
    所以思路就是,从上到下,依次求直方图最大面积矩形,感觉瞬间没有难度了。下面的代码里,第一个函数就是原封不动搬过来的。。

    时间复杂度是O(n^2)

    代码:

     1     int largestRectangleArea(vector<int> &height) {
     2         int maxArea = 0;
     3         int n = height.size();
     4         stack<int> st;
     5         int h, w;
     6 
     7         for (int i = 0; i < n; i++) {
     8             if (st.empty() || height[st.top()] < height[i])
     9                 st.push(i);
    10             else {
    11                 while (!st.empty() && height[st.top()] > height[i]) {
    12                     h = height[st.top()];
    13                     st.pop();
    14                     w = st.empty() ? i : i - (st.top() + 1);
    15                     maxArea = max(maxArea, h * w);
    16                 }
    17                 st.push(i);
    18             }
    19         }
    20 
    21         return maxArea;
    22     }
    23 
    24     int maximalRectangle(vector<vector<char> > &matrix) {
    25         if (matrix.empty() || matrix[0].empty())
    26             return 0;
    27 
    28         int maxArea = 0;
    29         int h = matrix.size();
    30         int w = matrix[0].size();
    31         vector<int> histo(w + 1, 0); // 在末尾增加一个0起收割作用
    32 
    33         for (int i = 0; i < h; i++) {
    34             // 计算直方图
    35             for (int j = 0; j < w; j++)
    36                 histo[j] = (histo[j] + 1) * (matrix[i][j] - '0');
    37 
    38             maxArea = max(maxArea, largestRectangleArea(histo));
    39         }
    40 
    41         return maxArea;
    42     }
  • 相关阅读:
    MySQL案例:一次单核CPU占用过高问题的处理
    编写你的第一个Django应用
    ks.cfg文件相关
    Kickstart部署多系统
    Kickstart部署之FTP架构
    Kickstart部署之HTTP架构
    Kickstart部署之NFS架构
    Kickstart无人值守原理及简介
    Linux下面Oracle实列实如何登录的
    welogic的受管理服务器无法启动
  • 原文地址:https://www.cnblogs.com/boring09/p/4231975.html
Copyright © 2011-2022 走看看