leetcode 习题解答:84. Largest Rectangle in Histogram

难度:hard

描述:

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 heights = [2,1,5,6,2,3],
return 10.


思路:

真的难,如果要暴力做的话O(N^2)复杂度,过不了。

上网一搜解答,发现了这个用栈来解决的算法,代码不长,但是看着很迷。

下面就以题目给的例子来看看这个算法怎么工作:

基本思路是维护一个递增的栈,就是说栈内的长条的长度都是递增的,绝不存在上层元素小于下层的情况。

但是这个栈为了方便计算面积,记录的是长条在题目给出的heights数组的索引而不是长度。

有记录最大面积的变量max ,初始化为0

所以我们就开始入栈:指针p在heights数组上从0开始递增

p = 0, 遇到2,入栈

p = 1,遇到1,小于栈顶元素,不能放进去了,要出栈:

首先记住栈顶的长度2,他是height,然后pop,这时栈为空。宽度直接为p,这时为什么呢?

我们知道,某个长条和另外长条一起计算面积且以它的长度为高,那么另外长条的长度一定不能小于它的长度,不然就不能以它的长度来作为合并出来的矩形的高了。

而我们维护的是个递增的栈,那么此时空栈意味着,该长条的左边不存在比他短的长条!所以可以直接用p来作为宽度

如果不为空呢?那么宽度为p-(stack.top+1),意思是矩形宽度到stack.top的前面,stack.top过短,挡住了矩形的延展。

然后求面积,如果大于max,就更新max。

最后整个栈都空了,最大面积也求出了,这个算法时间复杂度O(n)

很巧妙,但是理解起来很费解。

代码:

#include<stack>
class Solution {
public:
    
    int largestRectangleArea(vector<int>& heights) {
        if (heights.size() == 0) return 0;
        std::stack<int> s;
        int max = 0;
        int i = 0;
        while(i < heights.size()){
            if (s.empty() || heights[s.top()] <= heights[i]){
                s.push(i);
                i++;
            } else {
                int height = heights[s.top()];
                s.pop();
                int width = s.empty()?i:i-s.top()-1;
                if (width*height > max) max = width*height;
            }
        }
        while (!s.empty()) {              //  empty the stack
                int height = heights[s.top()];
                s.pop();
                int width = s.empty()?i:i-s.top()-1;
                if (width*height > max) max = width*height;
        }
        return max;
    }
};


LeetCode84 题的题目名称是: ## **Largest Rectangle in Histogram**(直方图中最大的矩形) --- ### 🔹题目描述: 给定一个非负整数数组 `heights`,它表示直方图中每个柱子的高度,每个柱子的宽度为 1。请你找出能围成的**最大矩形的面积**。 --- ### 🔹示例: ```text 输入: [2,1,5,6,2,3] 输出: 10 ``` 解释: 最大的矩形是由高度为 5 和 6 的两个柱子组成的,宽度为 2,面积 = 5 * 2 = 10。 --- ### 🔹解法思路: 这是一道非常经典的使用 **单调栈(Monotonic Stack)** 解决的问题,可以在 **O(n)** 时间内解决。 基本思路是: - 维护一个单调递增栈,栈中保存的是柱子的索引。 - 遇到一个比栈顶柱子矮的柱子时,说明当前栈顶柱子的“右边界”找到了,可以计算以它为高的最大矩形。 - 每个柱子只会进栈一次、出栈一次,保证了时间复杂度为 O(n)。 --- ### 🔹C++ 实现代码: ```cpp #include <iostream> #include <vector> #include <stack> using namespace std; int largestRectangleArea(vector<int>& heights) { stack<int> s; int maxArea = 0; heights.push_back(0); // 添加一个0,确保最后所有元素都会被处理 for (int i = 0; i < heights.size(); ++i) { while (!s.empty() && heights[i] < heights[s.top()]) { int height = heights[s.top()]; s.pop(); int width = s.empty() ? i : i - s.top() - 1; maxArea = max(maxArea, height * width); } s.push(i); } return maxArea; } int main() { vector<int> heights = {2,1,5,6,2,3}; cout << "最大矩形面积是: " << largestRectangleArea(heights) << endl; return 0; } ``` --- ### 🔹相关问题: 这个问题是很多类似问题的基础,例如: - 🧩 LeetCode 85. Maximal Rectangle(最大矩形,二维扩展) - 🧩 LeetCode 2560. 打家劫舍 IV(使用二分+DP,类似最大最小策略) - 🧩 POJ 2559 Largest Rectangle in Histogram(本题的经典原始版本) --- ### 🔹总结: | 项目 | 内容 | |------|------| | 难度 | 困难 | | 算法 | 单调栈 | | 时间复杂度 | O(n) | | 空间复杂度 | O(n) | | 相关题号 | LeetCode 85, 2560, 962 | --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值