zoukankan      html  css  js  c++  java
  • LeetCode:Largest Rectangle in Histogram(update)

    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.

    别人家的巧妙的代码:每次都维护一个递增的栈 比较栈顶与当前元素。如果当前元素小于栈顶元素,则入栈,否则合并现有栈,直至栈顶元素小于当前元素。结尾时

    入栈元素为0,重复合并一次。

     1 class Solution {
     2 public:
     3     int largestRectangleArea(vector<int>& height) {
     4         
     5          stack<int> s;
     6          
     7          int result=0;
     8          height.push_back(0);
     9          
    10          for(int i=0;i<height.size();i++)
    11          {
    12              if(s.empty()||height[s.top()]<height[i])
    13                 s.push(i);
    14               else{
    15                 
    16                      int index = s.top(); 
    17                      s.pop();
    18                      int width = s.empty() ? i : (i-s.top()-1);
    19                      result = max(result,height[index] * width);
    20                      i--;
    21         
    22               }
    23          }
    24          return result;
    25         
    26     }
    27 };
  • 相关阅读:
    班课6
    lesson one
    班课5
    ES6之Proxy及Proxy内置方法
    ES6模板字符串
    ES6之Symbol
    ES6对象及ES6对象简单拓展
    ES6函数的拓展
    ES6数组及数组方法
    ES6字符串方法
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4705087.html
Copyright © 2011-2022 走看看