[LeetCode]Container With Most Water

Description:
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

解析:这道题的题意是,有n条竖线(隔板),求任意两条竖线与x轴组成的木桶的面积。实际上就是哪两个木板组成的面积最大。

这道题第一眼看去就抛去了暴力手法,太麻烦了,而且时间复杂度肯定不够,所以得找到技巧(规律)。这道题找出规律就好做了。

当你在纸上画图,然后慢慢观察的时候,你会发现:假设两条木板L,R(R是离L最远的一条木板)。如果L < R,那么对于L来说,他能组成最大的面积就是(R-L)乘L。其它的任何木板组成的面积都是(R-L-n)乘L。

这样的话,我们就不需要一个一个比较了,代码也就出来了。

code:

public int maxArea(int[] height) {

        if(height == null)return 0;

        int len = height.length-1;
        int index = 0;
        int area = 0;
        int temp = 0;
        while(index < len){
            if(height[index] < height[len]){
                temp = (len-index)*height[index];
                index++;
            }
            else{
                 temp = (len-index)*height[len];
                 len--;
            }

            if(area < temp){
                area = temp;
            }
        }
        return area;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值