LeetCode No.84 Largest Rectangle in Histogram

来源:互联网 发布:毛利胜永 知乎 编辑:程序博客网 时间:2024/04/30 14:58

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
原创粉丝点击