zoukankan      html  css  js  c++  java
  • LeetCode——largest-rectangle-in-histogram1

    Question

    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 =10unit.

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

    Code

    /*
    用堆栈计算每一块板能延伸到的左右边界
    对每一块板
     堆栈顶更矮,这一块左边界确定,入栈
     堆栈顶更高,堆栈顶右边界确定,出栈,计算面积
     入栈时左边界确定
     出栈时右边界确定
     堆栈里元素是递增的
    本质:中间的短板没有用!
    复杂度 O(n)
    */
    
    class Solution {
    public:
        int largestRectangleArea(vector<int> &height) {
            stack<int> tb;
            int res = 0;
            for (int i = 0; i < height.size(); i++) {
               while (!tb.empty() && height[tb.top()] >= height[i]) {
                   int index = tb.top();
                   tb.pop();
                   if (tb.empty()) 
                       // 当前长度的最矮高度
                       res = max(i * height[index], res);
                   else {
                      // 底 * 高
                       res = max((i - tb.top() - 1) * height[index], res);
                   }
               }
               tb.push(i);
            }
            // 这里的n相当于相面的i遍历到height.size(); 
            // 所以用n来计算底的长度
            int n = height.size();
            while (!tb.empty()) {
                int index = tb.top();
                tb.pop();
                if (tb.empty())
                    // 最矮的列
                    res = max(n * height[index], res);
                else {
                    res = max((n - tb.top() - 1) * height[index], res);
                }
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    如何判断DataSet里有多少个DataTable
    ADO.NET五大对象详解
    c# 中的封装、继承、多态详解
    什么是递归算法
    反射是什么
    什么是泛型
    方法中参数的类型详细
    Struts2学习笔记二 配置详解
    Struts2学习笔记一 简介及入门程序
    Hibernate学习笔记四 查询
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7760459.html
Copyright © 2011-2022 走看看