【Leetcode】84. Largest Rectangle in Histogram(思维)(重点关注)

约定不等于承诺〃 2022-02-23 08:04 260阅读 0赞

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.

histogram.png
Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

histogram_area.png
The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

  1. Input: [2,1,5,6,2,3]
  2. Output: 10

题目大意:

给出一组序列,找出这组序列如果按柱状图来放置时能够形成的最大矩形面积。

解题思路:

这道题可以看似复杂,所以上去暴力一波肯定超时。其实暴力方法其中包含着大量的不必要操作。我们应该将注意力放在每个矩形的形成上,控制时间复杂度在O(n)左右。

根据短板效应,每个矩阵的形成取决于这一排中最短的那一根。当我们遍历到5这个长度时,我们其实只需要去考虑5能够形成最大矩阵,其中如图中画出的黄色和红色区域,并不取决5的大小,只与1和2这两个长度有关。

20190407144347957.png

知道了这些我们只需要知道1-n这些长度中属于自己矩形的左右边界即可。

所以第一个遍历从左到右,找到当前位置的左边界在哪里,判断条件为左边的长度比本位置大。

第二个遍历从右到左,找到当前位置的右边界在哪里,判断条件为右边的长度比本位置大。

最后遍历找出极大值。

注:这种题其实最恶心。还有个地方一定要注意,我们搜索时必须简化我们向前、向后搜索步骤,不然也会超时。比如全1的序列,我们不可能一位一位的比较,前一个比他大的数能够到达的位置,那么当前的数也能到达,所以不是p—而是p=l[p]。

  1. class Solution {
  2. public:
  3. int largestRectangleArea(vector<int>& heights) {
  4. int n = heights.size();
  5. vector<int> l(n,0),r(n,n);
  6. for(int i = 1;i<n;i++){
  7. int p = i-1;
  8. while(p>=0&&heights[p]>=heights[i]){
  9. p = l[p] - 1;
  10. }
  11. l[i] = p + 1;
  12. }
  13. for(int i = n-2;i>=0;i--){
  14. int p = i+1;
  15. while(p<n&&heights[p]>=heights[i]){
  16. p=r[p];
  17. }
  18. r[i] = p;
  19. }
  20. int ans = 0;
  21. for(int i = 0;i<n;i++){
  22. ans = max(ans, (r[i]-l[i])*heights[i]);
  23. }
  24. return ans;
  25. }
  26. };

发表评论

表情:
评论列表 (有 0 条评论,260人围观)

还没有评论,来说两句吧...

相关阅读