[leetcode] 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.

https://oj.leetcode.com/problems/container-with-most-water/

思路1:O(n^2)复杂穷举所有的情况,too young too simple.

思路2::两个指针i,j分别指向首位,选择二者中小的向中间移动(对于二者相等的情况,移动任意一个都可以),同时更新最大值。这个想法的基础是,如果i的长度小于j,如果移动j,短板在i,不可能找到比当前记录的area更大的值了,只能通过移动i来找到新的可能的更大面积。

public class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int maxA = 0;
        int curA = 0;
        int i = 0, j = n - 1;
        while (i < j) {
            if (height[i] <= height[j]) {
                curA = Math.abs(j - i) * height[i];
                if (curA > maxA)
                    maxA = curA;
                i++;
            } else {
                curA = Math.abs(j - i) * height[j];
                if (curA > maxA)
                    maxA = curA;
                j--;
            }
        }

        return maxA;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().maxArea(new int[] { 2, 2, 2 }));
        System.out.println(new Solution().maxArea(new int[] { 1, 2, 3 }));
        System.out.println(new Solution().maxArea(new int[] { 2, 3, 3 }));

    }

}

 

参考:

http://blog.csdn.net/wzy_1988/article/details/17248209

http://www.cnblogs.com/zhaolizhen/p/Containerwater.html

 

 

 

 

posted @ 2014-06-26 19:12  jdflyfly  阅读(228)  评论(0编辑  收藏  举报