leetcode练习:11. Container With Most Water

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 and n is at least 2.

刚开始是超时的答案(因为最傻的双重循环)

var maxArea = function(height) {
    var maxA = 0;
    var len = height.length;
    for(var i = 0;i<len;i++){
        for(var j=i+1;j<len;j++){
            var area = (height[i]<height[j]?height[i]:height[j])*(j-i);
            if(area > maxA)
                maxA = area;
        }
    }
    return maxA;
};

后来发现,我们可以完全避免掉一些答案。

我们来模拟一下~

按照常规的,我们需要把每一根配对比较~但是有的情况,其实是可以忽略的。首先先注意,我们的答案应该是X距离最远~且高距离又要小,这样才能让答案尽量大。

我们可以把它化为一重循环,即他的复杂度只有O(n)。

我们设置两个变量,分别从两端靠近比较,直到两个变量相等为止结束循环,其中~如果left的量要大于right,right就减一,相反,left就加一。我们就比较这种情况下所有面积的最大值。

最后AC的代码:

var maxArea = function(height) {
    var maxA = 0;
    var l = 0;
    var len = height.length;
    var r = len-1;
    
    if(len<2) return 0;
    
    while(l!=r){
        var v = (r-l)*Math.min(height[l],height[r]);
        if(v>maxA) maxA=v;
        if(height[l] < height[r]) {
            l++;
        } else {
            r--;
        }
    }
    return maxA;
};

当left向右移动的时候,我们就舍弃了left左边的所有线,因为它们组成的面积不可能会比后面的大。光想感觉还是很难想出来。目前宝宝试着证明了一下没有证明出明确的结果/(ㄒoㄒ)/~~

 

posted @ 2017-10-15 21:09  章鱼小年糕  阅读(115)  评论(0编辑  收藏  举报