zoukankan      html  css  js  c++  java
  • leetcode84 Largest Rectangle in Histogram

    思路:

    使用单调栈计算每个位置左边第一个比它矮的位置和右边第一个比它矮的位置即可。

    实现:

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 class Solution 
     4 {
     5 public:
     6     int largestRectangleArea(vector<int>& heights) 
     7     {
     8         int n = heights.size();
     9         vector<int> l(n, -1);
    10         stack<int> s;
    11         s.push(0);
    12         for (int i = 1; i < n; i++)
    13         {
    14             if (heights[s.top()] < heights[i])
    15             {
    16                 l[i] = s.top();
    17                 s.push(i);
    18             }
    19             else
    20             {
    21                 while (!s.empty() && heights[s.top()] >= heights[i])
    22                     s.pop();
    23                 if (!s.empty()) l[i] = s.top();
    24                 s.push(i);
    25             }
    26         }
    27         while (!s.empty()) s.pop();
    28         s.push(n - 1);
    29         vector<int> r(n, n);
    30         for (int i = n - 2; i >= 0; i--)
    31         {
    32             if (heights[s.top()] < heights[i])
    33             {
    34                 r[i] = s.top();
    35                 s.push(i);
    36             }
    37             else
    38             {
    39                 while (!s.empty() && heights[s.top()] >= heights[i])
    40                     s.pop();
    41                 if (!s.empty()) r[i] = s.top();
    42                 s.push(i);
    43             }
    44         }
    45         int ans = 0;
    46         for (int i = 0; i < n; i++)
    47         {
    48             ans = max(ans, heights[i] * (r[i] - l[i] - 1));
    49         }
    50         return ans;
    51     }
    52 };
    53 int main()
    54 {
    55     int a[] = {2, 1, 5, 6, 2, 3};
    56     vector<int> v(a, a + 6);
    57     cout << Solution().largestRectangleArea(v) << endl;
    58     return 0;
    59 }
  • 相关阅读:
    ​DBEngines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
    深入了解 BTree 和 B+Tree 的区别
    exec详解
    javascript之property's attributes
    极客公园之李彦宏讲话要点
    C++之auto_ptr
    javascript之属性状态控制Method
    ARM寄存器简介
    linux之fcntl
    http之100continue
  • 原文地址:https://www.cnblogs.com/wangyiming/p/9620942.html
Copyright © 2011-2022 走看看