标签:style blog http color 使用 io for 数据 ar
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
.
思路:每次选取当前区间内最小的值,计算面积:最小值*区间长度。然后,将当前区间划分为两个子区间,再以同样的方式处理子区间。这种方法实现起来非常复杂。
可以使用栈操作来更简洁地处理该问题。依次遍历输入数据,若当前元素大于栈顶元素,则入栈;否则,栈顶元素出栈,同时计算栈顶元素所在矩形的最大面积。这样做使得我们能同时确定出栈时栈顶元素左右两侧值比其小且距离最近的元素的位置。下面是网上看到的非常简洁的代码,通过在输入数组末尾加0,保证所有元素都会被出栈,从而获得正确结果:
1 class Solution { 2 public: 3 int largestRectangleArea( vector<int> &height ) { 4 height.push_back( 0 ); 5 stack<int> stk; 6 int i = 0, maxArea = 0; 7 while(i < height.size()){ 8 if( stk.empty() || height[stk.top()] <= height[i] ){ 9 stk.push(i++); 10 }else { 11 int t = stk.top(); 12 stk.pop(); 13 maxArea = max( maxArea, height[t] * ( stk.empty() ? i : i-stk.top()-1 ) ); 14 } 15 } 16 return maxArea; 17 } 18 };
Largest Rectangle in Histogram
标签:style blog http color 使用 io for 数据 ar
原文地址:http://www.cnblogs.com/moderate-fish/p/3928203.html