zoukankan      html  css  js  c++  java
  • 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.

    思路1:O(n^2),两层循环计算所有可能的矩阵面积。小数可以通过,大数级超时。

    class Solution {
    public:
        int largestRectangleArea(vector<int> &height) {
            int n=height.size();
            if(n==0)
                return 0;
            int maxArea;
            for(int i=0;i<n;i++)
            {
                int width=height[i];
                for(int k=i;k<n;k++)
                {
                    if(width*(n-i)<=maxArea)
                        break;
                    width=min(width,height[k]);
                    maxArea=max(maxArea,width*(k-i+1));
                }
            }
            return maxArea;
        }
    };

    思路2:使用一种单调递增的stack,可以用O(n)解决这道题目;主要是循环遍历,栈顶元素指向的heigh值如果小于height[i],则入栈i+1;如果大于height[i],则做这样的处理——将栈顶元素取出,这是有两种情况1)栈为空,则此时的area为目前的height值乘以i;2)栈不为空,计算此时的area。从而比较得到最大maxArea;

    注意:一定要在height后面添加一元素0或者其他较小值,保证当可以对最后一个元素进行操作。

    class Solution {
    public:
        int largestRectangleArea(vector<int> &height) {
            int n=height.size();
            if(n==1)
                return height[0];
            int maxArea=0;
            int area;
            stack<int> s;
            height.push_back(0);
            for(int i=0;i<=n;)
            {
                if(s.empty()||height[s.top()]<=height[i])
                {
                    s.push(i++);
                }
                else
                {
                    int k=s.top();
                    s.pop();
                    if(s.empty())
                    {
                        area=height[k]*i;
                    }
                    else
                    {
                        area=height[k]*(i-s.top()-1);
                    }
                    maxArea=max(maxArea,area);
                }
            }
            return maxArea;
        }
    };
  • 相关阅读:
    P2420 让我们异或吧(倍增)
    bzoj题目分类
    hash练习们
    bzoj1433[ZJOI2009]假期的宿舍(匈牙利)
    bzoj2427:[HAOI2010]软件安装(Tarjan+tree_dp)
    bzoj2730矿场搭建(Tarjan割点)
    codevs4511信息传递(Tarjan求环)
    进入js
    css层叠样式表
    HTML超文本标记语言
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3763302.html
Copyright © 2011-2022 走看看