Leetcode 11. Container With Most Water

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.

原题链接:Container With Most Water

  题目可以这么理解,在i位置有条高为ai的竖线,让你选出两台竖线构成一个容器,使得该容器装的水最多,注意容器不能倾斜。

          |
  |       |
  |       |    
  |   |   | |     |
| |   |   | | |   |
| | | | | | | | | | | 
0 1 2 3 4 5 6 7 8 9 10 

  如上图,横纵都为一个单位,我们很容易看出来1和9位置组成的容器容积最大,所盛水为24个单位。大家都知道桶的容积是有最短的一条木板决定的,在这副二维图中是由短的一条边决定的。
   没有什么问题是通过暴力解决不了的,这道题也是,我们直接暴力选取两条边,算最大容积就好了,时间复杂度O(n^2)。 显然,这并不是最优解,其实还有O(n)的解法。
  我们用两个指针l和r分别从两头往中间移动,直到重合,记录下移动过程中最大的容积。 移动的策略是如果height[l] < height[r] l右移,反之r左移。 代码很简单,但是很难理解,为啥这样就算出正确答案了??
  想想看,容器的容积是有最短的一条边决定的,l和r如果你把长边向中间移动的话,容积只会减少不会增加,对不,所以移动长边是无意义的。但是移动短边,有可能短边会变长,容积可能变大。不知道我说清楚了吗,反正这就是大体的思路,很明显这是O(n)的时间复杂度。

代码如下:

public class Solution {
    public int maxArea(int[] height) {
        if (height.length < 2) return 0;
        int ans = 0;
        int l = 0;
        int r = height.length - 1;
        while (l < r) {
            int tmp = (r - l) * Math.min(height[l], height[r]);
            if (v > ans) 
                ans = tmp;
            if (height[l] < height[r]) 
                l++;
            else r--;
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xindoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值