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

推荐订阅源

C
Check Point Blog
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
腾讯CDC
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
Vercel News
Vercel News
P
Proofpoint News Feed
雷峰网
雷峰网
博客园_首页
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
V
V2EX
F
Fortinet All Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog
S
SegmentFault 最新的问题

博客园 - 谢绝围观

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;
}