• 用栈解决Largest Rectangle问题


    一问题描述


    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.将max_area置为0,声明一个栈s,s为存储对应方块的下标,且s为递增栈,具体做法将在下面继续说明

                    2.若栈为空或者当前矩形高度大于s的头元素对应的矩形高度,则其下标入栈,否则出栈,并计算出栈元素对应矩形高度的面积,更新max_area,直至当前头元素对应矩形高度小于将要入栈的矩形。

                    3.若最后栈非空,则将栈中元素一一出栈,并计算相应的面积,更新max_area。

                    4.最后的max_area为所求。

    三算法原理说明


                 1.关于步骤2中出栈元素求其面积:

                      由于栈s为递增栈,故当当前矩形高度小于s中头元素(设为i)对应的矩形高度时,s出栈,出栈后s(若不空)的头元素设为top1,则出栈矩形对应的宽度为(i - top1 - 1),画个图更便于理解,注意s空时,应为i。

                   2.关于步骤3中出栈元素求其面积:

                          对应于s出栈元素对应矩形的宽度应为size - top1 - 1(栈不空,size为整个输入矩形的宽度,top1同上定义),注意若栈空,则宽度为size。

    四代码示例


      int largestRectangleArea(vector<int>& height) {
      int maxArea =0, top = 0, top1 = 0;
      int size = height.size();
      stack<int> sInt;
      if(!height.empty())
      {
        for(int i = 0; i < size; i++)
        {
          if(sInt.empty() || height[sInt.top()] < height[i])
            sInt.push(i);
          else
          {
            if(!sInt.empty())
            top = sInt.top();
            sInt.pop();
            if(!sInt.empty())
            top1 = sInt.top();
            int width = sInt.empty()? i: i - top1 - 1;
            maxArea = max(maxArea, height[top] * width);
            i--;
          }
        }
      }

      //栈非空
      while(!sInt.empty())
      {
        top = sInt.top();
        top1 = 0;
        sInt.pop();
        if(!sInt.empty())
        top1 = sInt.top();
        int width = (sInt.empty())? size: (size - top1 - 1);
        maxArea = max(maxArea, height[top] * width);
      }
      return maxArea;

  • 相关阅读:
    Python自动化运维之20、HTML
    Python自动化运维之18、Python操作 MySQL、pymysql、SQLAchemy
    Python自动化运维之17、Python操作 Memcache、Redis、RabbitMQ
    Python自动化运维之16、线程、进程、协程、queue队列
    Python自动化运维之15、网络编程之socket、socketserver、select、twisted
    Python自动化运维之14、设计模式
    Python自动化运维之13、异常处理及反射(__import__,getattr,hasattr,setattr)
    浏览器学习笔记-11 settimeout
    浏览器学习笔记-10 页面中的一些优化
    浏览器学习笔记--09 事件循环
  • 原文地址:https://www.cnblogs.com/YJthua-china/p/4960578.html
Copyright © 2020-2023  润新知