【leetcode】 Largest Rectangle in Histogram

介绍三种解决直方图最大矩形面积问题的方法,包括遍历递增序列、使用双栈记录高度与索引及单栈记录索引的方式,并提供每种方法的详细步骤与示例代码。

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

from : https://leetcode.com/problems/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 height = [2,1,5,6,2,3],
return 10.

思路1:

按递增的顺序,找到最右边的一个递增位置,然后从这个位置往前逐个检查,更新最大面积。

时间复杂度为O(n^2)。

public class Solution {
    public int largestRectangleArea(int[] height) { 
          int area = 0;  
          for (int i = 0; i < height.length; i++) {  
            for (int k = i + 1; k < height.length; k++) {  
              if (height[k] < height[k - 1]) {  
                i = k - 1;  
                break;  
              } else {  
                i = k;  
              }  
            }  
            int lowest = height[i];  
            for (int j = i; j >= 0; j--) {  
              if (height[j] < lowest) {  
                lowest = height[j];  
              }  
              int currArea = (i - j + 1) * lowest;  
              if (currArea > area) {  
                area = currArea;  
              }  
            }  
          }  
          return area;  
        
    }
}

思路2:

用两个栈,一个表示当前的高度,一个表示当前的下标。

heightStack 和 indexStack;表示当前递增的元素下标和值的对应关系。也许有人疑问,为什么不直接存下标。看上面的图,对于Y=5这个点,它对应的下标最后会被更新为1,即Y=7的位置,在Y=4这个点,其面积为(4-1+1)*4,如果Y=5的下标不是1,而是其本身,那么Y=4可以延伸出的面积就少了。

相当于到Y=4这个点的时候,栈中表示的图形变为途中黑色区域:

这么说可能看不明白,看来代码和后面(1),(2)的解释应该会明白了。

1.在递增或者相等的情形下,入栈;在遇到减少的时候出栈计算。逐个计算当前面积并更新最大面积。

2.最后,将剩余栈中元素处理一下。

注意下面代码中的(1)和(2)处。

public class Solution {
    public int largestRectangleArea(int[] height) {
		int area = 0 , len = height.length;
		Stack<Integer> heightStack = new Stack<Integer>();
		Stack<Integer> indexStack = new Stack<Integer>();
		for (int i = 0; i < len; i++) {
			if (heightStack.empty() || heightStack.peek() <= height[i]) {
				heightStack.push(height[i]);
				indexStack.push(i);
			} else if (heightStack.peek() > height[i]) {
				int j = 0;
				while (!heightStack.empty() && heightStack.peek() > height[i]) {
					j = indexStack.pop();
					int currArea = (i - j) * heightStack.pop();
					if (currArea > area) {
						area = currArea;
					}
				}
				heightStack.push(height[i]); // (1)
				indexStack.push(j); // (2)
			}
		}
		while (!heightStack.empty()) {
			int currArea = (len - indexStack.pop())	* heightStack.pop();
			if (currArea > area) {
				area = currArea;
			}
		}
		return area;
	}
}

(1)和(2)表示:

j此时指向第一个比height[i]大的元素;对于新的栈中情况,此时要将height[i]和j对应起来,这样两个栈才表示尚未完成面积计算的元素。如果不明白,可以用例子[2,1,3]模拟一下,简单说明:

栈的情况如下:

1.

heightStack :2

indexStack  :0

2.

heightStack :1

indexStack  :0

3.

heightStack :1 1

indexStack  :0 1

4.

heightStack :1 1 3

indexStack  :0 1 2


其实,用一个栈,加上自定义的结点,可以更快更好处理。代码如下:

public class Solution {
    class Node {
        int i;
        int h;
        public Node(int i, int h) {
            this.i = i;
            this.h = h;
        }
    }
    public int largestRectangleArea(int[] height) {
		int area = 0, len=height.length;
		Stack<Node> lines = new Stack<Node>();
		for(int i=0; i<len; ++i) {
		    if(lines.isEmpty() || lines.peek().h <= height[i]) {
		        lines.add(new Node(i, height[i]));
		    } else {
		        int k = 0, h = height[i];
		        while(!lines.isEmpty() && lines.peek().h > h) {
		            Node node = lines.pop();
		            k = node.i;
		            int cur = (i-k)*node.h;
		            if(cur > area) {
		                area = cur;
		            }
		        }
		        lines.add(new Node(k, h));
		    }
		}
		
		// last clear
		while(!lines.isEmpty()) {
		    Node node = lines.pop();
		    int cur = (len-node.i)*node.h;
		    if(cur > area) {
		        area = cur;
		    }
		}
		
		return area;
	}
}

思路3:

基本跟上一个思路一致,区别在于只用一个栈放下标。

思路2中,下标主要用来计算宽度,那么这里不去对应高度和下标,如何做到?

这个栈存放的是当前递增height数组的子数组的下标,注意,自增数组不需要连续;其实思路二也是。也就是[1,2,5,4]这个数组的子数组可是是[1,2,4]。这个栈中的子数组是递增的。这个题目的过程一直是找到当前(当前指数组下标为i之前)最后一个递增子数组,在i之前的子数组,找到其中的最大面积。按照上面的例子,当i=4,前栈的状态时<0,2,3>。那么看下面(*)处的代码,可以知道栈顶元素对应的高度是其高度,这个高度对应的矩形的宽度则是栈中下一个元素(即下标)+1与当前栈顶元素的位置的举例。具体还是看代码。

//(*)中,stack空表示指向了下标为-1的地方,那么i-(-1)-1 = i。 所以计算如下。

public class Solution {
    public int largestRectangleArea(int[] height) {
		int area = 0, len=height.length;
		Stack<Integer> stack = new Stack<Integer>();
		for (int i = 0; i < len; ++i) {
			if (stack.empty() || height[stack.peek()] < height[i]) {
				stack.push(i);
			} else {
				int start = stack.pop();
				int width = stack.empty() ? i : i - stack.peek() - 1;
				area = Math.max(area, height[start] * width);
				--i;
			}
		}
		while (!stack.empty()) {
			int start = stack.pop();
			int width = stack.empty() ? len : len- stack.peek() - 1;//(*)
			area = Math.max(area, height[start] * width);
		}
		return area;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值