[LeetCode] Largest Rectangle in Histogram

本文介绍了一种高效求解直方图中最大矩形面积的算法。通过使用栈来记录柱子的高度及其索引,避免了传统的O(n^2)复杂度问题。文章详细解释了算法的工作原理,并给出了具体的实现代码。

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.


这道题,第一眼看去,直观思路是对于每一根柱子,左右扩展,但是这样O(n^2) 超时

对于一根柱子,保存其左侧所有比其高度要高的柱子,那么就可以知道以这根柱子为右边界的面积

实际上这里只需要保存左侧可以匹配的高度以及其下标即可

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int maxArea = 0;
        if(height.size() == 0) return 0;
        
        stack<int> hStack;
        stack<int> iStack;
        
        for(int i = 0; i < height.size(); i++) {
            if(hStack.empty() || height[i] > hStack.top()) {
                hStack.push(height[i]);
                iStack.push(i);
            }
            else if(height[i] < hStack.top()) {
                int lastIndex = 0;
                while(!hStack.empty() && height[i] < hStack.top()) {
                    lastIndex = iStack.top();
                    iStack.pop();
                    int tmpHeight = hStack.top();
                    hStack.pop();
                    int tmpArea = tmpHeight*(i - lastIndex);
                    if(tmpArea > maxArea) maxArea = tmpArea;
                }
                hStack.push(height[i]);
                iStack.push(lastIndex);
            }
        }
        
        while(!hStack.empty()) {
            int tmpArea = hStack.top()*(height.size() - iStack.top());
            hStack.pop();
            iStack.pop();
            if(tmpArea > maxArea) maxArea = tmpArea;
        } 
        return maxArea;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值