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 height = [2,1,5,6,2,3]
,
return 10
. 學習
題目分析:spa
題意很是清楚,就是尋找直方圖中的最大矩形面積。code
看似很是簡單,最早想到的方法就是窮舉法,從頭開始日後尋找,或者經過剪枝肯定可能的右邊界向前尋找,時間複雜度O(n2)。這個算法顯然在數據不少或者遞增遞減的圖中會掛掉。blog
根據助教的提示,下面考慮使用棧:博客
經過觀察能夠發現,矩形必定在夾在兩個較小的矩形的中間,並且必定有矩形右邊的元素高度小於矩形最左端的元素的高度,例如上圖中高度2小於矩形最左端高度5。it
也就是說計算的矩形必定是一個相似」波峯「的形狀。io
從而咱們能夠從頭遍歷集合,當遇到大於當前棧頂元素高度的元素時,進棧;不然,依次出棧,直到棧頂小於等於當前高度,計算面積。並將當前元素壓入棧內。
此解法的核心思想爲:一次性計算連續遞增的區間的最大面積,而且考慮完成這個區間以後,考慮其前、後區間的時候,不會受到任何影響。也就是這個連續遞增區間的最小高度大於等於其前、後區間。
代碼以下:
class Solution { public: int largestRectangleArea(vector<int>& height) { stack<int> index_height; height.push_back(0); //加入立柱0,做爲結尾判斷 int area = 0; for (int i = 0; i < height.size(); i++) { if (index_height.empty() || (!index_height.empty() && height[i] >= height[index_height.top()])) //若是比棧頂的高度大,則進棧,構建單調棧 index_height.push(i); else { //比棧頂的高度小,開始依次出棧,並記錄下標 while (!index_height.empty() && height[index_height.top()] > height[i]) { int index = index_height.top(); index_height.pop(); int width = index_height.empty() ? i : (i - index_height.top() - 1); //計算彈出的面積 area = max(area, height[index] * width); } index_height.push(i); // 將當前進棧 } } return area; } };
提交到OJ,能夠AC經過。但發現廣泛C語言的程序速度更快,想了很久,覺得有什麼更好地方法。後來想到,C語言裏沒有用棧,直接順序存儲的數組訪問起來更加快。 0.0
此博客中的內容均爲原創或來自網絡,不用作任何商業用途。歡迎與我交流學習,個人郵箱是lsa0924@163.com