Container With Most Water

    public int maxArea(int[] height) {
        //http://blog.csdn.net/linhuanmars/article/details/21145429 贪心算法要看看
        if(height==null || height.length<2) return 0;
        int max = 0;
        int l=0, h = height.length-1;
        while(l<h){
            max = Math.max(max,Math.min(height[l], height[h])*(h-l));
            if(height[l]<height[h]){
                l++;
            }else{
                h--;
            }
        }
        return max;
        
    }

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.

 

题解抄自code ganker

“首先一般我们都会想到brute force的方法,思路很简单,就是对每一对pair都计算一次容积,然后去最大的那个,总共有n*(n-1)/2对pair,所以时间复杂度是O(n^2)。 
接下来我们考虑如何优化。思路有点类似于Two Sum中的第二种方法--夹逼。从数组两端走起,每次迭代时判断左pointer和右pointer指向的数字哪个大,如果左pointer小,意味着向左移动右pointer不可能使结果变得更好,因为瓶颈在左pointer,移动右pointer只会变小,所以这时候我们选择左pointer右移。反之,则选择右pointer左移。在这个过程中一直维护最大的那个容积。

posted @ 2015-04-10 12:22  世界到处都是小星星  阅读(96)  评论(0编辑  收藏  举报