第四周:84. Largest Rectangle in Histogram

来源:互联网 发布:被网络监控 编辑:程序博客网 时间:2024/06/05 11:18

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.

Subscribe to see which companies asked this question.

这道题我做的时候忽略很多问题,我一开始思路是相邻的计算其面积,代码如下:

 int i=0,j;int maxarea=0;int temp;if(heightsSize==1)return heights[0];else{while(i<heightsSize){j=i+1;if(heights[i]!=0){if(heights[i]<heights[j]) temp=heights[i]*2;elsetemp=heights[j]*2;if(maxarea<temp)maxarea=temp;}i++;}return maxarea;}
这导致出现以下的错误:



看来是我的思路出问题了,无论怎么修改总会出现一些数据的错误,于是这道题我求助网上面所说的解法,利用栈去进行求解。

代码:

class Solution {public:    int largestRectangleArea(vector<int>& heights) {       stack<int> stk;        int len = heights.size();        int maxArea = 0;        for (int i = 0; i < len; i++)        {            if (stk.empty() || stk.top() <= heights[i])                stk.push(heights[i]);            else            {                int count = 0;                while (!stk.empty() && stk.top() > heights[i])                {                    count++;                    maxArea = max(maxArea, stk.top()*count);                    stk.pop();                }                while (count--)                    stk.push(heights[i]);                stk.push(heights[i]);            }        }        int count = 1;        while (!stk.empty())        {            maxArea = max(maxArea, stk.top()*count);            stk.pop();            count++;        }        return maxArea;    } };

0 0