Largest_Rectangle_in_Histogram

来源:互联网 发布:易语言网页填表源码 编辑:程序博客网 时间:2024/06/09 16:53

题目描述:

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));}}