[LeetCode OJ] Largest Rectangle in Histogram

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.

 

方法一:两层循环遍历,复杂度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)