惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
人人都是产品经理
人人都是产品经理
V
Visual Studio Blog
博客园 - 叶小钗
A
About on SuperTechFans
Last Week in AI
Last Week in AI
量子位
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
T
The Blog of Author Tim Ferriss
Vercel News
Vercel News
博客园 - 司徒正美
博客园 - Franky
博客园 - 【当耐特】
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
J
Java Code Geeks

博客园 - 谢绝围观

LeetCode 910. Smallest Range II EAC 抓取CD为AAC文件 Binary Indexed Tree (Fenwick Tree) Lint Code 1365. Minimum Cycle Section LintCode 896. Prime Product 简明题解 UVa 1471 - Defense Lines Windows下安装配置MinGW GCC调试环境 详解LeetCode 137. Single Number II LeetCode 309. Best Time to Buy and Sell Stock with Cooldown 修改注册表删除Windows资源管理器 “通过QQ发送” 右键菜单项 LeetCode 312. Burst Balloons LeetCode 287. Find the Duplicate Number LeetCode 10. Regular Expression Matching LeetCode 117. Populating Next Right Pointers in Each Node II 在Windows Azure VM下搭建SSTP VPN - 谢绝围观 利用.NET Code Contracts实现运行时验证 Log4net 配置实例 解决Windows Server 2012 下利用RRAS创建VPN断线的问题 - 谢绝围观 慎用静态类static class
LeetCode 84. Largest Rectangle in Histogram
谢绝围观 · 2017-02-11 · via 博客园 - 谢绝围观

O(N)时间+O(N)空间复杂度。代码如下:

int largestRectangleArea(vector<int>& heights) {
    if (heights.empty()) {
        return 0;
    }

    vector<int> bars;
    bars.push_back(0);
    int maxArea = 0;
    // 在原数组最后增加一个高度为0的bar,这样可以保证最终所有在stack里的bar都被弹出,而不需在循环结束时再单独处理一遍stack里的bar
    heights.push_back(0);
    for (int i = 1; i < heights.size(); i++) {
        int currentHeight = heights[i];
        while (!bars.empty() && currentHeight <= heights[bars.back()]) {
            int k = bars.back();
            int h = heights[k];
            bars.pop_back();
            // 处理刚弹出的bar k,假设前一个元素的index为j,则bar的宽度w为: 左边宽度(k - j) + 右边宽度(i - k -1) = i - j - 1.
            // 解释:
            // 左边从 k 到 j 是被bar k弹出的元素,显然它们都比k高,加上k本身,宽度即为k - j。
            // 右边是被新元素 i 弹出的元素,显然他们也比 k 高,否则之前 k 就被它们弹出了。
            int w = bars.empty() ? i : (i - bars.back() - 1);
            int area = h * w;
            maxArea = max(maxArea,area);
        }
        bars.push_back(i);
    }
    return maxArea;
}