leetcode 84. Largest Rectangle in Histogram

33 篇文章 0 订阅
30 篇文章 0 订阅

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.
在这里插入图片描述
在这里插入图片描述Example:

Input: [2,1,5,6,2,3]
Output: 10

tag: array, stack

method 1

暴力解:两重循环,从i出发,进行第二次遍历,第二次遍历中,每一步都比较高度,得到可以用来作为高的最小高度,然后计算面积,最后存储最大面积

public int largestRectangleArea(int[] heights) {
        int max = 0;
        for (int i = 0; i < heights.length; i++) {
            int area = heights[i];
            int minHeight = heights[i];
            for (int j = i + 1; j < heights.length; j++) {
                minHeight = Math.min(minHeight, heights[j]);
                area = Math.max(area, (j - i + 1) * minHeight);
            }

            max = Math.max(area, max);
        }
        return max;
    }

method 2

对于每一个bar x,将barx 看作最小的一个bar

思想与method1一样,但是更巧妙

以i位置为中心,找到往左往右最后一个不小于height[i]的位置left,right,然后面积就为height[i]*(right-left-1)

但往左往右找的过程中,也要一个一个地遍历,这样的话仍然是n^2的复杂度,因此作出了改进

使用两个数组lessFromLeft记录往左最后一个不小于height[i]的位置,lessFromRight记录往右最后一个不小于height[i]的位置

The only line change shifts this algorithm from O(n^2) to O(n) complexity: we don’t need to rescan each item to the left - we can reuse results of previous calculations and “jump” through indices in quick manner:

复用之前的计算结果,因为如果height[p]>=height[i]的话,那显然lessFromLeft[p]中存储的值x也符合height[x]<height[i]

public int largestRectangleArea2(int[] heights) {
        if (heights == null || heights.length == 0) {
            return 0;
        }
        int[] lessFromLeft = new int[heights.length]; // idx of the first bar the left that is lower than current
        int[] lessFromRight = new int[heights.length]; // idx of the first bar the right that is lower than current
        lessFromRight[heights.length - 1] = heights.length;
        lessFromLeft[0] = -1;

        for (int i = 1; i < heights.length; i++) {
            int p = i - 1;
            while (p >= 0 && heights[p] >= heights[i])
                p = lessFromLeft[p];

            lessFromLeft[i] = p;
        }

        for (int i = heights.length-2; i >= 0; i--) {
            int p = i + 1;
            while (p < heights.length && heights[p] >= heights[i])
                p = lessFromRight[p];

            lessFromRight[i] = p;
        }

        int max = 0;
        for (int i = 0; i < heights.length; i++) {
            max = Math.max(max, heights[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
        }

        return max;
    }

method3

使用栈,思想和method2一致,也是找到i位置上往左往右最后一个大于height[i]的位置

所以遍历数组,如果当前i的高度大于栈顶索引的高度,那么将i push进去,如果当前i的高度小于栈顶tp的高度,那么说明i是tp往右找第一个小于height[tp]的位置,那往左找第一个小于height[tp]的位置在哪?就是当前的栈顶tp’.为什么是当前栈顶?可以联想为什么tp会被加入栈,就是因为for遍历到tp(i)时,因为height[tp] > height[tp’] (tp’是当时的栈顶),所以tp才会压入栈,成为新栈顶.

只能说太神了,感觉将栈运用得灵活自如

public int largestRectangleArea3(int[] height) {
    int len = height.length;
    Stack<Integer> s = new Stack<Integer>();
    int maxArea = 0;
    for(int i = 0; i <= len; i++){
        int h = (i == len ? 0 : height[i]);
        if(s.isEmpty() || h >= height[s.peek()]){
            s.push(i);
        }else{
            int tp = s.pop();
            maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
            i--;
        }
    }
    return maxArea;
}

method4

分治法

RMQ思想,区间最值查询

public int largestRectangleArea4(int[] height) {
        if (height.length == 0)
            return 0;
        return largestRectangleArea(height, 0, height.length - 1);
    }

    private int largestRectangleArea(int[] height, int start, int end) {
        if (start == end)
            return height[start];

        int mid = start + (end - start) / 2;
		//计算左半边的面积
        int area = largestRectangleArea(height, start, mid);
		//计算右半边的面积
        area = Math.max(area, largestRectangleArea(height, mid + 1, end));
		//计算经过中间点的面积
        area = Math.max(area, largestRectangleArea(height, start, mid, end));

        return area;
    }

    private int largestRectangleArea(int[] height, int start, int mid, int end) {
        int i = mid, j = mid + 1;

        int area = 0;
        int h = Math.min(height[i],height[j]);
        while (i >= start && j <= end){
            h = Math.min(h,Math.min(height[i],height[j]));
            area = Math.max(area,h * (j-i+1));
            if (i == start)
                j++;
            else if (j == end)
                i--;
            else {
                if (height[i-1] > height[j+1])
                    i--;
                else j++;
            }
        }

        return area;
    }

summary

  1. 通过复用之前的计算结果来避免扫描每一项,降低复杂度
  2. 凡是涉及往左往右查找的,都可以尝试运用分治法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值