zoukankan      html  css  js  c++  java
  • [LeetCode] Maximal Rectangle(good)

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

    参考“Largest Rectangle in Histogram”这个题的解法,思想差不多一样,只是用h向量表示Rectangle中此元素中第一行到本行的高度,非常妙的算法:

    class Solution {
    public:
        int maximalRectangle(vector<vector<char> > &matrix) {
            if(matrix.size() == 0 || matrix[0].size() == 0)
                return 0;
            int cLen = matrix[0].size();
            int rLen = matrix.size();
            //height array
            vector<int> h(cLen+1,0);
        
            int max = 0;
    
            for(int row = 0;row<rLen;row++){//for(1)
               stack<int> s;
               for(int i=0;i<cLen+1;i++){//for(2)
                   if(i<cLen){
                      if(matrix[row][i]=='1')
                          h[i] += 1;
                      else
                          h[i] = 0;
                   }//end if
    
                   if(s.empty() || h[s.top()]<=h[i]){
                       s.push(i);
                   }else{
                       while(!s.empty() && h[i]<h[s.top()]){
                          int top = s.top();
                          s.pop();
                          int area = h[top]*(s.empty()?i:(i-s.top()-1));
                          if(area > max)
                              max = area;
                       }//end while
                       s.push(i);
                   }//end if
               }//end for(2)        
            }//end for(1)
            return max;
        }//end func
    };
  • 相关阅读:
    MySql 数据类型
    MySql 数据库的增删改
    MySql 联合查询
    Mysql 库的管理 --->>>>DDL
    MySql 子查询
    MySql 分页查询
    sql99语法的连接查询
    MySql 连接查询
    MySql 分组函数
    jQ处理页面中尺寸过大的图片
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3914469.html
Copyright © 2011-2022 走看看