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;
        }
    };
  • 相关阅读:
    find 以及linux 和windows 文件互传
    27 关于Object类 -- equals()
    26 super关键字
    25 访问修饰符限定词
    24 继承 子类中方法重写
    23 static 关键字
    22 包(package)来解决不同包下同名文件的冲突问题
    21 封装(get,set方法)
    20 带参构造方法(this关键字)
    19 无参构造方法
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3763302.html
Copyright © 2011-2022 走看看