LeetCode84 Largest Rectangle in Histogram
問題鏈接 LeetCode84
問題描述
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.
問題分析
這道題和之前那道盛水的題目有幾分類似的樣子,也是可以通過暴力破解的方式來解決,但是超時了。於是從網上找到了一種利用棧的算法。
算法描述:
- 維護一個棧,要求棧自下而上是升序排列,在遍歷給定數組的過程中嗎,如果當前數組元素小於棧頂的元素。那麼執行出棧操作,直到棧頂元素小於當前數組元素。
- 如果執行出棧操作,那麼如何計算出棧的元素所形成的矩形面積呢。經過分析可以看出面積爲當前數組元素的座標和出棧元素數組座標的差乘以出棧元素的高度。
- 如果遍歷完棧不爲空,那麼需要從棧頂元素開始,對當前棧內所有的元素進行面積計算,計算公式爲 = 出棧元素的高度 * (數組最後的座標-元素出棧後的棧頂元素座標)
因爲在計算過程中會出現棧爲空的現象,爲了方便處理,在棧底放入座標-1的元素,方便計算。
代碼如下
public int largestRectangleArea(int[] heights) {
if(heights==null ||heights.length<1){
return 0;
}
int result = 0;
Stack<Integer> stack = new Stack<>();
stack.add(-1);
for(int i=0;i<heights.length;i++){
while(stack.size()!=1 && heights[stack.peek()]>=heights[i]){
//出棧直到棧頂元素小於當前元素或棧內元素只有一個
//在出棧的過程中計算出棧元素形成的面積。因爲已出站的元素肯定大於待出棧的元素,所以面積就是座標差乘以待出棧的元素高度。
result = Math.max(heights[stack.pop()]*(i-stack.peek()-1),result);
}
//當前元素入棧
stack.add(i);
}
//遍歷完後,如果棧不爲空,取當前棧頂的座標
int right = stack.peek();
while (stack.size()>1){
//繼續出棧,出棧元素的面積爲(座標right-未出棧棧頂座標)*已出站元素高度
result = Math.max(heights[stack.pop()]*(right-(stack.peek())),result);
}
return result;
}
LeetCode學習筆記持續更新
GitHub地址 https://github.com/yanqinghe/leetcode
CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678