[leetcode]Container With Most Water 和Largest Rectangle in Histogram

这两题看起来有点像,但是实际上是完全不一样的,区别在于:

The "Container With Most Water" solution will allow the water to rise above intermediate positions. With the "largest rectangle" problem, the rectangle cannot rise above intermediate bars.
也就是说 Container With Most Water只考虑左右边界,[i,j]范围内的Area = min(height[i],height[j]) * (j-i); Largest Rectangle in Histogram,高度最小值为[i,j]范围内所有高度的最小值。后者比前者要难很多
1. Container With Most Water
对于这题,考虑左右边界[i,j] ,当height[i]<height[j]时,因为i是其中的短板,则无论j取[i+1,j]中的任何值,Area都只会比当前已求出的[i,j]的Area小(横坐标范围减小,再遇见比height[i]更小的右边界),因此以i为左边界的情况不再考虑,i++;反之,j--,同样的思考方式。
代码:
public class Solution {
    public int min(int i,int j){
        return i<j?i:j;
    }
    public int maxArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(height == null) return 0;
        int i = 0;
        int j = height.length -1;
        int max = 0;
        
        while(i<j){
            int area = min(height[i],height[j])*(j-i);
            if(area>max) max = area;
            if(height[i]<height[j]) i++;
            else j--;
        }
        return max;
    }
}
 
Largest Rectangle in Histogram 
代码如下:
public int largestRectangleArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(height == null) return 0;
        int len = height.length;
        Stack<Integer> stack = new Stack<Integer>();
        Stack<Integer> width = new Stack<Integer>();//记录向左可以扩展的宽度
        int max = 0;
        stack.push(0);
        width.push(0);
        
        int h;
        for(int i = 0;i<=len;i++){ 
            if(i == len) h = 0;
            else h = height[i];
            int wid = 0;
            while(h<stack.peek()){
                //1.算自己的左边界
                //2.已放入栈中的高度>h的右边界已经找到了
                int top = stack.pop();
                wid += width.pop();
                max = Math.max(max,top*wid);
                }
            stack.push(h);
            width.push(Math.max(wid+1,1));//每次加入stack的时候,他的左边界就已经确定了
           
        }
        return max;
    }
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值