『Leetcode』Largest Rectangle in Histogram

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.

Solution_1

  如果不限制时间复杂度的话,O(n^2)的时间复杂度可以很容易实现代码。

之前的一个比较简单的实现:

public static int largestRectangleArea(int[] height) {
    if (height == null || height.length <= 0) return 0;
    int maxArea = 0;
    for (int i = 0; i < height.length; i++) {
        int minHeight = height[i];
        for (int j = i; j < height.length; j++) {
            if (height[j] < minHeight) {
                minHeight = height[j];
            }
            int tempArea = minHeight * (j - i + 1);
            if (tempArea > maxArea) {
                maxArea = tempArea;
            }
        }
    }
    return maxArea;
}

  即最直接的思路,考虑所有可能的window,然后找出最小高度,然后计算面积。显然,O(n^2)的时间复杂度不能AC。

Solution_2

  然后借鉴水中的鱼-[LeetCode] Largest Rectangle in Histogram 解题报告,采用stack来进行计算,使得时间复杂度降低到O(n)。

  1. 初始化Stack<Integer> stack,并在数组末尾添加0。
  2. 遍历数组,如果当前数字大于stack.peek(), 则将顶端数字pop出来,并计算面积大小与maxArea取最大,直到顶端数字小于当前数字。
  3. 返回maxArea。

代码如下:

public class Solution {
   public int largestRectangleArea(int[] height) {
        Stack<Integer> stack = new Stack<Integer>();
        int[] h = new int[height.length + 1];
        h = Arrays.copyOf(height, height.length + 1);

        int i = 0; 
        int maxArea = 0;
        while(i < h.length){
            if(stack.isEmpty() || h[i] >= h[stack.peek()])
                stack.push(i++);
            else{
                int temp = stack.pop();
                maxArea = Math.max(maxArea, h[temp]*(stack.isEmpty()?i:(i-stack.peek()-1)));
            }
        }
        return maxArea;
   }
}

  大致思路为:当数组为递增的时候,如[1,2,3,4,5],类似这种的时候,我们其实可以直接计算1x5, 2x4, 3x3, 4x2, 5x1,然后比较最大即可。

  以上的算法即为不断的找出递增数列然后计算面积的过程。通过上述算法虽然AC,但是时间27 ms,只能beat 30%左右,究其原因,是test case中存在大量的递增序列,导致算法本身O(2n),比不上直接O(n).

可以稍加改进,增加如下代码:

boolean sorted = true;
int l = height.length;
for (int i = 0; i < l; i++) {
   if (i > 0 && height[i] < height[i - 1]) 
      sorted = false;
}
if (sorted) {
   int max = 0;
   for (int i = 0; i < l; i++) {
      max = Math.max(max, height[i] * (l - i));
   }
   return max;
}

将特殊的test cases 特殊处理,AC,时间降低为6ms,beat92%。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值