• largest rectangle in histogram leetcode


    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.

    思路分析:暴力破解方法应该不需要多说,直接计算每一个元素所能构成的最大矩形面积,并与max比较并记录。

    这道题,是看了网上的众多博客之后结合自己的理解来mark一下这个过程(最主要是一遍就解决了,时间复杂度O(n)):

      用到了栈,栈顶元素,跟当前索引是关键:

        入栈:如果栈为空或者栈顶元素(其在直方图中的对应高度)小于等于当前索引(对应高度),这样就使得,栈中的元素(对应高度)是非递减的。这样符合贪心算法的思想,因为若是当前索引(对应高度)大于栈顶元素(对应高度),则继续入栈,因为必然能得到更大的矩形面积,贪心!

        出栈:当前索引(对应高度)<栈顶元素(对应高度),则栈顶元素出栈,并记录下其对应高度,并计算其能对应的最大矩形面积。注意一个关键点:栈顶元素跟当前索引之间的所有元素(对应高度)都大于等于这两个端点对应高度!

     1 class Solution {
     2 public:
     3     int largestRectangleArea(vector<int>& height) {
     4         stack<int> sta;
     5         height.push_back(0);
     6         int i = 0,sum=0;
     7         while (i < height.size())
     8         {
     9             if (sta.empty() ||height[sta.top()] <= height[i])
    10             {
    11                 sta.push(i++);
    12             }
    13             else
    14             {
    15                 int t = sta.top();
    16                 sta.pop();
    17                 sum = max(sum, height[t]*(sta.empty()?i:i - sta.top() - 1));
    18             }
    19         }
    20         return sum;
    21     }
    22 };
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    【转载】jyupter notebook入门指南
    【转载】CnBlogs博文排版
    【转载】如何知道自己适合做什么
    【转载】讲真,认知几乎是人和人之间唯一的本质差别。
    Geekband C++面向对象高级程序设计-第六周课程5
    Geekband C++面向对象高级程序设计-第六周课程3
    Outlier实验-补充记录1
    Outlier实验-出错记录1
    Geekband C++面向对象高级程序设计-第六周课程2
    Geekband C++面向对象高级程序设计-第六周课程1
  • 原文地址:https://www.cnblogs.com/chess/p/4750961.html
Copyright © 2020-2023  润新知