Leetcode 11 Container With Most Water

来源:互联网 发布:怎么理解js面向对象 编辑:程序博客网 时间:2024/06/06 13:09

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

最容易想到的做法是n方暴力扫两边,但是看到题目难度是medium之后,我就知道一定有更优美的做法。

对,就是用两点法,其实本质是一种贪心,先说思路再来解释原理。

以起始点为两端向中间缩,记录面积的最大值,每次向内移动高度较小的一方。

因为向内移动每次X轴上的长度都会减少1,所以要想获得更大的面积就必须依赖于Y轴上的长度增加,

而Y长度由两端的较小者决定,所以移动高度较小的一方。

这里就有问题了,如果两者高度一样该怎么办呢?我想了有一会儿。

在高度一样的情况下,随便移动哪一端都是没有问题的!

因为向中间移的过程中,真正有可能刷新最大面积的是两个更高的Y轴长度,

所以如果中间还有面积更大的情况,不论先移动哪一边,最后都一定会移动至两个更高的位置。

class Solution {public:    int maxArea(vector<int>& height) {        int l=0,r=height.size()-1;        int result=0;        while(l<r)        {            result=max(result,(r-l)*min(height[l],height[r]));            if(height[l]<height[r])                l++;            else                r--;        }        return result;    }};


0 0