leetCode练习(84)

题目:Largest Rectangle in Histogram

难度:hard

问题描述:

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.

解题思路:求最大矩形。很难的一道题,我是看了提示使用了stack才解出来。stack中存储的是方块的下标索引号,如果当前方块的高度大于等于栈顶元素对应方块的高度,那么就将该方块的索引号进栈。那么每个栈元素的下面一层就是它的左边界。当遇到当前方块的高度小于栈顶元素对应方块的高度,则出栈,出栈元素的右边界则为当前方块。然后再将当前元素入栈。这样每个元素都会入栈,下一层就是左边界,每个元素都会出栈,使它出栈的元素则是它的右边界。

当所有元素便利后,剩余栈内元素的右边界就是len-1.

具体代码如下:

public static int largestRectangleArea(int[] heights) {
        int len=heights.length;
        int res=0;
        int temp;
        int left=0,right=0;
        int i;
        Stack<Integer> stack=new Stack<>();
        for(i=0;i<len;i++){
        	if(stack.isEmpty()){
        		stack.push(i);
        		continue;
        	}
        	while(!stack.isEmpty()){
        		if(heights[stack.peek()]<=heights[i]){
        			break;
        		}else{
        			temp=stack.pop();
        			right=i-1;
        			if(stack.isEmpty()){
        				left=0;
        			}else{
        				left=stack.peek()+1;       				
        			}
        			res=res>(right-left+1)*heights[temp]?res:(right-left+1)*heights[temp];       		
        		}			
        	}
        	stack.push(i);     	
        }   
        while(!stack.isEmpty()){
    		int top=heights[stack.pop()];
    		int size=top*(stack.isEmpty()?i:i-stack.peek()-1);
    		res=Math.max(res, size);
    	}
        return res;
    }




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值