Leetcode-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.


Seen this question in a real interview before?   

Yes
 

先说下思路:

看了Leetcode上第一个讨论答案给出来的方法,可能是最简单的方案,构造堆栈的方式去做。

首先考虑如果给出的heights里的数是从小到大排好序的,那么最大阴影面积应该为:max{第一条形高度*条形数量,第二个条形高度*(条形数量-1),以此类推),因此这是发现这是一个可直接表示的算法。

现在考虑普世情况,也就是没有排序好,那么考虑用栈的方式将其转换为排序好的条形:

以题目中给出的2,1,5,6,2,3为例,初始result=0;

(1)2入栈,{2},result=0;

(2)发现1比2小,2弾栈,且计算result=2*1=2;再将2替换为1重新入栈,然后再将1入栈,栈中情况为{1,1};

(3)5入栈,{1,1,5},result = 2;

(4)6入栈,{1.1.5.6},result=2;

(5)发现2比6小,于是6弾栈,并计算result=max(6*1,2)=6,然后发现2比5还要小,于是5再弾栈,计算result=max(result,5*2)=10,此时再将5和6都替换为2入栈,此时栈中为{1,1,2,2},result=10.

(6)3入栈{1,1,2,2,3}

最后计算此升序栈的最大结果为max(1*5,1*4,2*3,2*2,3*1)=6,6<10,因此得出最终result=10.

下面给出代码,注释部分为用vector容器来表示栈,实则一样。

/*class Solution
{
public:
	int largestRectangleArea(vector& heights){
		vector stack;//通过构建升序栈的方式解决这个问题
		int m = heights.size();
		int result =0;
		for(int i=0;i=stack.back()||stack.empty()){
				stack.push_back(heights[i]);
			}
			else{
				int count =0;
				while(heights[i] &height) {
        int ret = 0;
        stack stk;
        for(int i = 0; i < height.size(); i ++)
        {
            if(stk.empty() || stk.top() <= height[i])
                stk.push(height[i]);
            else
            {
                int count = 0;
                while(!stk.empty() && stk.top() > height[i])
                {
                    count ++;
                    ret = max(ret, stk.top()*count);
                    stk.pop();
                }
                while(count --)
                    stk.push(height[i]);
                stk.push(height[i]);
            }
        }
        int count = 1;
        while(!stk.empty())
        {
            ret = max(ret, stk.top()*count);
            stk.pop();
            count ++;
        }
        return ret;
    }
};


你可能感兴趣的:(Leetcode)