zoukankan      html  css  js  c++  java
  • 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.

    算法分析:有两种方法,第一种暴力法,利用两重循环,求[i,j]之间最大的矩形面积。第二种方法利用栈,栈中存放递增的索引。

    方法一:brute force

    //brute force,用两重循环,求[i,j]之间最小值
    	public static int largestRectangleArea(int[] heights)
    	{
    		int minHeight = 0;
    		int maxArea = 0;
    		for(int i = 0; i < heights.length; i ++)
    		{
    			for(int j = i; j < heights.length; j ++)
    			{
    				if(i == j)
    				{
    					minHeight = heights[i];
    				}
    				else
    				{
    					if(heights[j] < minHeight)
    					{
    						minHeight = heights[j];
    					}
    				}
    				int temp = minHeight * (j - i + 1);
    				if(maxArea < temp)
    				{
    					maxArea = temp;
    				}
    			}
    		}
    		return maxArea;
        }
    

     方法二:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

    //利用栈和单调性
    	public static int largestRectangleArea2(int[] heights)
    	{
    		Stack<Integer> stack = new Stack<>();
    		int[] h = Arrays.copyOf(heights, heights.length + 1);//h最后元素补0,为了让所有元素出栈,所以补0
    		int i = 0;
    		int maxArea = 0;
    		while(i < h.length)
    		{
    			if(stack.isEmpty() || h[stack.peek()] <= h[i])
    			{
    				stack.push(i++);//只存放单调递增的索引
    			}
    			else
    			{
    				int t = stack.pop();//stack.isEmpty说明i是栈里最小的元素,面积为i*h[t]
    				maxArea = Math.max(maxArea, h[t]*(stack.isEmpty() ? i : i-stack.peek()-1));
    			}
    		}
    		return maxArea;
    	}
    
  • 相关阅读:
    安卓开发之有序广播
    安卓开发之无序广播
    安卓开发之短信发送器的开发
    安卓开发之隐式意图与显示意图
    安卓root权限 被提示Read-only file system 或 Operation not permitted 解决方案
    gcc 的基本使用和静态库、动态库的制作与使用
    Python类的学习,看这一篇文章就够了!
    Qt 添加程序图标和系统托盘图标
    Qt ListWidget item 发起拖放
    Qt 接受拖放
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5803426.html
Copyright © 2011-2022 走看看