码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-84 Largest Rectangle in Histogram

时间:2015-03-18 01:08:26      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

思路:计算以height[i]为最低点时的最大面积。

1. 创建一个栈stack;

1. 从头开始遍历数组,如果数组为空或者当前遍历元素height[i]>=stack.peek(),就将"i"进栈,注意是将"i"而不是height[i];

3. 如果height[i]<stack.peek();

  计算以height[stack.pop()]为最短高度,长度为i-stack.peek()-1的面积;

  如果此时stack为空,则长度为"i";

  如果计算得到的面积大,则更新当前最大面积max;

4. 当遍历到数组结束时,添加一个元素“0”作为终点判断。

 

代码如下:

public int largestRectangleArea(int[] height) {
        if(height == null || height.length < 1) 
            return 0;
        
        Stack<Integer> stack = new Stack<Integer>();
        int max = 0;
        int current = 0;
        for(int i=0; i<=height.length;) {
            if(i == height.length) {
                current = 0;
            } else {
                current = height[i];
            }
            
            if(stack.isEmpty() || current >= height[stack.peek()]) {
                stack.push(i);
                i++;
            } else {
                int h = height[stack.pop()];
                int length = (stack.isEmpty() ? i : i-stack.peek()-1);
                max = Math.max(max, h*length);
            }
        }
        return max;
    }

LeetCode-84 Largest Rectangle in Histogram

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4345848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!