LeetCode刷题笔录Largest Rectangle in Histogram

本文探讨了如何解决LeetCode中的一道题目——寻找直方图中最大的矩形面积。通过使用栈来存储高度递增的直方图柱子的索引,当遇到比栈顶元素高度小的柱子时,依次弹出栈顶元素并计算面积。该算法复杂度为O(n),对于非负整数表示的直方图高度,能有效找出最大矩形面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

我真的只会brute force的方法,就是对每一个height,遍历之前的所有height,计算一遍area。这里可以稍微prune一下,就是当height[i+1]>=height[i]时,最大面积一定不会以height[i]结尾,因此可以跳过height[i]。不过这样算法的时间复杂度还是O(n^2)

public class Solution {
    public int largestRectangleArea(int[] height) {
        if(height == null || height.length == 0)
            return 0;
        int maxArea = height[0];
        for(int i = 1; i < height.length; i++){
            if(i < height.length - 1 && height[i] <= height[i + 1])
                continue;
            int minHeight = height[i];
            for(int j = i; j >= 0; j--){
                minHeight = Math.min(height[j], minHeight);
                maxArea = Math.max(maxArea, minHeight * (i - j + 1));
            }
        }
        
        return maxArea;
    }
}


O(n)的解法只能看大神的,确实神,不过不是很难理解。

可以知道每一个最大area一定会包含至少一个完整的hist。这样如果用这个完整的hist的高度去求面积,只要知道宽度就行了。如果现在有几个从左往右递增的高度,那么把这些index存到一个stack里。直到遇到第一个height小于stack顶元素的hist,则开始一个一个的pop出stack的元素并以当前stack顶元素作为最小的高度求面积。

看这里的解说吧,明白一些。

public class Solution {
    public int largestRectangleArea(int[] height) {
        if(height == null || height.length == 0)
            return 0;
        int maxArea = height[0];
        
        Stack<Integer> s = new Stack<Integer>();
        int i = 0;
        while(i < height.length){
            if(s.isEmpty() || height[i] >= height[s.peek()]){
                s.push(i);
                i++;
            }
            else{
                int top = s.pop();
                int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
                maxArea = Math.max(maxArea, area);
            }
        }
        
        while(!s.isEmpty()){
            int top = s.pop();
            int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
            maxArea = Math.max(maxArea, area);

        }
        
        return maxArea;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值