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

Largest Rectangle in Histogram

时间:2014-11-29 15:54:38      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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.

参考:http://blog.csdn.net/abcbc/article/details/8943485

C++实现代码:

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Solution
{
public:
    int largestRectangleArea(vector<int> &height)
    {
        if(height.empty())
            return 0;
        int maxArea=0;
        int i=0;
        int n=height.size();
        stack<int> st;
        int start;
        for(i=0;i<n;i++)
        {
            if(st.empty()||height[i]>height[st.top()])
                st.push(i);
            else
            {
                start=st.top();
                st.pop();
        //注意求宽度时,是减去当前元素的前一个栈顶元素的index
int width=st.empty()?i:i-st.top()-1; maxArea=max(width*height[start],maxArea); i--;//处理到栈为空或者栈中的元素都比当前处理的元素小为止 } } while(!st.empty()) { start=st.top(); st.pop(); int width=st.empty()?n:n-st.top()-1; maxArea=max(width*height[start],maxArea); } return maxArea; } }; int main() { Solution s; vector<int> height={1,2,2}; cout<<s.largestRectangleArea(height)<<endl; }

自己写的一个O(n^2)超时了。

#include<iostream>
#include<vector>
#include<climits>
using namespace std;

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        if(height.empty())
            return 0;
        int i,j;
        int minH;
        int maxArea=0;
        int n=height.size();
        for(i=0;i<n;i++)
        {
            minH=height[i];
            for(j=i;j<n;j++)
            {
                minH=min(minH,height[j]);
                maxArea=max(maxArea,minH*(j-i+1));
            }
        }
        return maxArea;
    }
};

int main()
{
    Solution s;
    vector<int> height={2,1,5,6,2,3};
    cout<<s.largestRectangleArea(height)<<endl;
}

 

Largest Rectangle in Histogram

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/wuchanming/p/4130764.html

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