• 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.

    参考: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;
    }
  • 相关阅读:
    边缘计算的爆发为安防全产业带来了怎样的变化?
    Kali卸载AWVS的方法
    C++最简打开网页的方法
    C# 打开指定文件或网址
    C# 如何获取某用户的“我的文档”的目录
    基于Debian的linux系统软件安装命令
    C#的基础知识
    MYSQL语句中的增删改查
    将博客搬至CSDN
    【易懂】斜率DP
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4130764.html
Copyright © 2020-2023  润新知