LeetCode No.84 Largest Rectangle in Histogram

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 heights = [2,1,5,6,2,3],
return 10.

====================================================================================================================================

这道题目的大意是:求出给定柱形图的最大长方形面积。

刚看到这道题的时候,我想应该不是很难,只要确定一个柱体为中点,然后记录不小于该柱体高度的往左走的最小left和往右走的最大right,然后求(right-left+1)*height的最大值就行了,这种做法的时间复杂度为O(N^2)。但是题目难度级别是hard,如果O(N^2)的算法都能过的话那不就很尴尬了,果不其然,TLE了。那有没有O(N*logN)甚至是O(N)的算法可以解决这个问题呢?

答案是有的,先放一个最小的0在高度序列的后面(预处理最后操作)从左往右扫一遍柱体,用一个vector记录这个严格递增的高度序列对应的下标,但出现不是严格递增的高度时,记录下此时最大矩阵,公式为:ans = max ( ans , heights[j] * ( hs.empty() ? i : i - hs.back() - 1 ) ) ,这样的时间复杂度便是O(N)了。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        heights.push_back ( 0 ) ;
        vector <int> hs ;
        int i = 0 , ans = 0 ;
        while ( i < heights.size() )
        {
            if ( hs.empty() || heights[i] > heights[hs.back()] )
            {
                hs.push_back ( i ++ ) ;
            }
            else
            {
                int j = hs.back () ;
                hs.pop_back () ;
                ans = max ( ans , heights[j] * ( hs.empty() ? i : i - hs.back() - 1 ) ) ;
            }
        }
        return ans ;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值