码迷,mamicode.com
首页 > 其他好文 > 详细

84. Largest Rectangle in Histogram

时间:2018-10-25 14:18:47      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:which   cpp   img   idt   tco   分享图片   efficient   where   size   

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.

 

Example:

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

my code:(very inefficient)

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        int res = 0;
        for (int i = 0; i < len; ++i) {
            int nums = 1;
            for (int j = i+1; j < len; ++j) {
                if (heights[j] >= heights[i])
                    nums++;
                else 
                    break;
            }
            for (int k = i-1; k >= 0; --k) {
                if (heights[k] >= heights[i])
                    nums++;
                else
                    break;
            }
            res = max(res, heights[i]*nums);
        }
        return res;
    }
};
Runtime: 1664 ms, faster than 1.28% of C++ online submissions for Largest Rectangle in Histogram.

 

height efficient code:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        int res = 0;
        stack<int> s;
        heights.push_back(0);
        for (int i = 0; i <= len; ++i) {
            int h = i==len ? 0 : heights[i];
            while (!s.empty() && h < heights[s.top()]) {
                int height = heights[s.top()];
                s.pop();
                int start = s.empty() ? -1 : s.top();
                int nums = i - start - 1;
                res = max(res, height*nums);
            }
            s.push(i);
        }
        
        return res;
    }
};

Runtime: 12 ms, faster than 45.96% of C++ online submissions for Largest Rectangle in Histogram.

stack中的数据(索引)升序进行排列,遇到小于前面的数开始计算,并将stack中比当前元素大的数pop。

 

84. Largest Rectangle in Histogram

标签:which   cpp   img   idt   tco   分享图片   efficient   where   size   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9849075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!