• 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;
    }
  • 相关阅读:
    如何加速JavaScript 代码
    以Kafka Connect作为实时数据集成平台的基础架构有什么优势?
    Java多线程开发系列之一:走进多线程
    java运行环境和运行机制
    C#先序遍历2叉树(非递归)
    Java 之 List<T> 接口的实现:ArrayList
    string.split() 解读---------->从java 和C#的角度剖析
    究竟什么是语法糖呢
    Eclipse 恢复删除的文件
    Notepad++自动刷新文本
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4130764.html
Copyright © 2020-2023  润新知