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

Leetcode: Largest Rectangle in Histogram

时间:2014-12-12 22:09:45      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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.

bubuko.com,布布扣

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

 

bubuko.com,布布扣

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.  

分析:这道题解法参考,leetcode.pdf, 解法很巧妙。该题思想的入手点跟Container with Most Water类似,高度最矮的那个柱子决定矩形的面积,所以我们可以按每个柱子为中心向两侧扩展知道遇到比该柱子矮的柱子,但时间复杂度是O(n^2),超时。

改进方法也是上面的思想,但它利用栈很好的维护了上面方法中以一个柱子为最小高度的矩形的左右界,从而将时间复杂度降为O(n)。还有一个trick是将height最后多加一个0,便于处理height只有一个元素和元素全是递增的情况。代码如下:

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        stack<int> S;
        height.push_back(0);
        int result = 0;
        
        for(int i = 0; i < height.size();){
            if(S.empty() || height[i] > height[S.top()])
                S.push(i++);
            else{
                int tmp = S.top();
                S.pop();
                result = max(result, height[tmp]*(S.empty()?i:i-S.top()-1));
            }
        }
        return result;
    }
};

 

Leetcode: Largest Rectangle in Histogram

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4160429.html

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