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

[LeetCode OJ] Largest Rectangle in Histogram

时间:2014-07-21 10:04:43      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   width   io   

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.

bubuko.com,布布扣

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

 

bubuko.com,布布扣

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.

 

方法一:两层循环遍历,复杂度O(n2

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int> &height) {
 4         int maxArea=0;
 5         for(unsigned i=0; i<height.size(); i++)
 6         {
 7             int min = height[i];
 8             for(unsigned j=i; j<height.size(); j++)
 9             {
10                 if(height[j]<min)
11                     min = height[j];
12                 int area = min*(j-i+1);
13                 if(area>maxArea)
14                     maxArea = area;
15             }
16         }
17         return maxArea;
18     }
19 };

 

方法二:用堆栈保存重要位置,复杂度O(n)

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int> &height) {  //用堆栈来实现
 4         stack<unsigned> st;
 5         unsigned maxArea = 0;
 6         for(unsigned i=0; i<height.size(); i++)
 7         {
 8             if(st.empty())
 9                 st.push(i);
10             else
11             {
12                 while(!st.empty())
13                 {
14                     if(height[i]>=height[st.top()])
15                     {
16                         st.push(i);
17                         break;
18                     }
19                     else
20                     {
21                         unsigned idx=st.top();
22                         st.pop();
23                         unsigned leftwidth = st.empty() ? idx : (idx-st.top()-1);
24                         unsigned rightwidth = i - idx-1;
25                         maxArea = max(maxArea, height[idx]*(leftwidth+rightwidth+1));
26                     }
27                 }
28                 if(st.empty())
29                     st.push(i);
30             }
31         }
32         unsigned rightidx = height.size();
33         while(!st.empty())
34         {
35             unsigned idx = st.top();
36             st.pop();
37             unsigned leftwidth = st.empty() ? idx : (idx-st.top()-1);
38             unsigned rightwidth = rightidx - idx-1;
39             maxArea = max(maxArea, height[idx]*(leftwidth+rightwidth+1));
40         }
41         return maxArea;
42     }
43 };

[LeetCode OJ] Largest Rectangle in Histogram,布布扣,bubuko.com

[LeetCode OJ] Largest Rectangle in Histogram

标签:style   blog   http   color   width   io   

原文地址:http://www.cnblogs.com/Marrybe/p/3856070.html

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