标签:empty for 位置 tin src mil 1.4 技术 div
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 =10unit.
For example, Given height =[2,1,5,6,2,3], return10.
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int> &height) { 4 int result = 0; 5 stack<int> s; 6 int n = height.size(); 7 for(int i=0;i<n;i++) 8 { 9 if(s.empty() || height[i] >= s.top()) 10 { 11 s.push(height[i]); 12 } 13 else 14 { 15 int count = 0; 16 while(!s.empty() && s.top() > height[i]) 17 { 18 count ++; 19 result = max(result, s.top()*count); 20 s.pop(); 21 } 22 while(count --)//弹出的位置用当前值替换 23 s.push(height[i]); 24 s.push(height[i]);//将当前值放入栈中 25 } 26 } 27 int count = 1; 28 while(!s.empty()) 29 { 30 result = max(result, s.top()*count); 31 s.pop(); 32 count ++; 33 } 34 return result; 35 } 36 };
leetcode栈--2、largest-rectangle-in-histogram(直方图最大面积)
标签:empty for 位置 tin src mil 1.4 技术 div
原文地址:http://www.cnblogs.com/qqky/p/6939768.html