zoukankan      html  css  js  c++  java
  • LeetCode-Largest Rectangle in Histogram

    Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.


    Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


    The largest rectangle is shown in the shaded area, which has area = 10 unit.

    For example,
    Given height = [2,1,5,6,2,3],
    return 10.

    一个栈,栈底的元素小于栈顶,每次压入新元素之前弹出所有大于新元素的就元素

    所有点进栈一次,出栈时确认该点为最小值的作用域(起点为栈内上一个元素下标的后一位,终点为当前压入元素下标前一位) 复杂度O(n)

    class Solution {
    public:
        int largestRectangleArea(vector<int> &height) {
            if(height.size()==0)return 0;
            stack<pair<int,int> > sta;
            pair<int,int> p,q;
            int max=0;
            int start,end,area;
            for(int i=0;i<height.size();i++){
                p.first=height[i];
                p.second=i;
                if(sta.size()==0){
                    sta.push(p);
                }
                else{
                    while(sta.top().first>p.first){
                        q=sta.top();
                        sta.pop();
                        end=i-1;
                        if(sta.size()==0){
                            start=0;
                            area=q.first*(end-start+1);
                            if(area>max)max=area;
                            break;
                        }
                        else{
                            start=sta.top().second+1;
                            area=q.first*(end-start+1);
                            if(area>max)max=area;
                        }
                        
                    }
                    if(sta.size()!=0){
                        if(sta.top().first==p.first){
                            sta.top().second=i;
                        }
                        else{
                            sta.push(p);
                        }
                    }
                    else{
                        sta.push(p);
                    }
                }
            }
            end=height.size()-1;
            while(sta.size()!=0){
                q=sta.top();
                sta.pop();
                if(sta.size()==0){
                    start=0;
                    area=q.first*(end-start+1);
                    if(area>max)max=area;
                }
                else{
                    start=sta.top().second+1;
                    area=q.first*(end-start+1);
                    if(area>max)max=area;
                }
            }
            return max;
        }
    };
    View Code
  • 相关阅读:
    hive on hbase
    django多表操作
    django单表操作
    django模板
    django路由初识
    python 相关模块安装 国内镜像地址
    django初识
    Python中属性和描述符的简单使用
    pip安装包(python安装gevent(win))
    jQuery 事件方法
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353184.html
Copyright © 2011-2022 走看看