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.

(给定n个非负整数表示柱状图的条高如果每个条的宽度为1,则在柱状图中找到最大矩形的面积。以上是一个柱状图,每个栏的宽度为1,高度= [ 2,1,5,6,2,3 ]。最大矩形显示在阴影区域,面积为10单位。)


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.

思路:这个题只能想出来从每个窗口向两边扩张找面积的方法,时间复杂度为平方级,当然了OJ系统肯定不会给你过的,又想不出来别的方法,网上看见一个很厉害的方法( 线性复杂度解法)(PS:这篇文章倒数第三张图里面黄框的面积标错了,应该是最左边标到1和2之间),挺巧妙的,思想蛮厉害的。翻译一下就是:如果已知heights数组是升序的比如1,2,5,7,8那么就是(1*5) vs (2*4) vs (5*3) vs (7*2) vs (8*1)也就是max(height[i]*(size-i))那么我们现在就要用栈来构造这样一个构造这样的升序序列。如果你比左面和你相邻的柱状图小(或者比右边和你相邻的柱状图大),那么最左面的柱状图只能和其左面的构成矩形,和右面的构不成矩形,因为你比他小了。如果你比右面和你相邻的柱状图小(或者比左边和你相邻的柱状图大),那么你还可以和右面的柱状图构成矩形,故将其入栈,构成升序序列。


public class Largest_Rectangle_in_Histogram {
	public static int largestRectangleArea(int[] heights) 
	{
		if(heights.length==0)
			return 0;
		int result = 0;
		//存放的是序列的下标
		Stack<Integer> stack = new Stack<Integer>();
		for(int i=0;i<heights.length;i++)
		{
			while(!stack.isEmpty()&&heights[i]<heights[stack.peek()])
			{
				int index = stack.pop();
				int height = heights[index];
				//这句话说白了就是如果你是最后一个出栈的,那说明你就是之前最小的数,那么你的宽就是i.
				int width = stack.isEmpty()?i:i-stack.peek()-1;
				result = Math.max(result,width*height);
			}
			stack.push(i);
		}
		while(!stack.isEmpty())
		{
			int index = stack.pop();
			int height = heights[index];
			int width = stack.isEmpty()?heights.length:heights.length-stack.peek()-1;
			result = Math.max(result,width*height);
		}
        return result;
    }
	public static void main(String[] args) {
		int heights[] = {2,1,2};
		System.out.println(largestRectangleArea(heights));
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值