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

    Description

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

    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
        
    Return 6.
    

    思路

    • 把这个矩阵分成第一行,第一二行,第一二三行。。来看,
    • 然后用84中的栈的方法求出当前的最大矩阵即可。

    代码

    class Solution {
    public:
        int maximalRectangle(vector<vector<char>>& matrix) {
            int m = matrix.size();
            if(m == 0) return 0;
            int n = matrix[0].size();
            if(n == 0) return 0;
            
            vector<int> nums(n, 0);
            int res = 0;
            for(int i = 0; i < m; ++i){
                for(int j = 0; j < n; ++j){
                    if(matrix[i][j] == '1')
                        nums[j] += 1;
                    else nums[j] = 0;
                }
                res = max(res, maxRectangle(nums, n));
            }
            
            return res;
        }
        
        int maxRectangle(vector<int>&nums, int len){
            stack<int> stk;
            int res = 0;
            int h = 0, t = 0;
            for(int i = 0; i < len; ++i){
                while(!stk.empty() && nums[stk.top()] > nums[i]){
                    h = nums[stk.top()];
                    stk.pop();
                    
                    t = stk.empty() ? i : i - stk.top() - 1;
                    res = max(res, h * t);
                }
                stk.push(i);
            }
            
            while(!stk.empty()){
                h = nums[stk.top()];
                stk.pop();
                
                t = stk.empty() ? len : len - stk.top() - 1;
                res = max(res, h * t);
            }
            return res;
        }
    };
    
  • 相关阅读:
    Lightmaping
    Android内存回收机制
    基本光照模型简单实现
    Pass的通用指令开关
    使用Depth Texture
    使用替换shader渲染
    Windows下安装Oracle12C(一)
    SpringMVC文件上传基础
    Spring集成线程池
    《经久不衰的Spring框架:@ResponseBody 中文乱码》(转)
  • 原文地址:https://www.cnblogs.com/lengender-12/p/7003838.html
Copyright © 2011-2022 走看看