首页 > 技术文章 > Container With Most Water

masterlibin 2016-05-25 22:04 原文

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.

题意:在二维坐标系中,(i, ai) 表示 从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积。

因为是盛水,所以要取短板。

两层 for 循环的暴力法会超时。

有没有 O(n) 的解法?

答案是有,用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。

 

public class MaxArea {

    public static int maxArea(int[] height)
    {
        int i = 0;
        int len = height.length;
        if(len <= 1)
            return 0;
        int area = 0;
        while(i < len-1)
        {
            int temp = Math.min(height[i], height[len-1])*(len-1-i);
            if(temp > area)
                area = temp;
            if(height[i] < height[len-1])
                i ++;
            else
                len --;
        }
        return area;
    }
    
    
    public static void main(String[] args) {
        int[] a = {1,1};
        System.out.println(maxArea(a));
    }

}

 

推荐阅读