码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Largest Rectangle in Histogram(update)

时间:2015-08-05 17:50:54      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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         
 5          stack<int> s;
 6          
 7          int result=0;
 8          height.push_back(0);
 9          
10          for(int i=0;i<height.size();i++)
11          {
12              if(s.empty()||height[s.top()]<height[i])
13                 s.push(i);
14               else{
15                 
16                      int index = s.top(); 
17                      s.pop();
18                      int width = s.empty() ? i : (i-s.top()-1);
19                      result = max(result,height[index] * width);
20                      i--;
21         
22               }
23          }
24          return result;
25         
26     }
27 };

 

LeetCode:Largest Rectangle in Histogram(update)

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4705087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!