码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Container With Most Water

时间:2015-12-15 14:04:01      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

思路:

1)两个for循环,遍历所有情况,时间O(n^2). 超时了.

package area;

public class ContainerWithMostWater {

    public int maxArea(int[] height) {
        int n = height.length;
        int maxArea = 0;
        for (int i = 0; i < n - 1; ++i) {
            for (int j = i + 1; j < n; ++i) {
                int area = Math.min(height[i], height[j]) * (j - i);
                if (maxArea < area)
                    maxArea = area;
            }
        }
        
        return maxArea;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

 

2)用两边夹的方式解决。设Aij为坐标(ai, aj)所圈定的区域面积,其中j > i,则Aij = min(ai, aj)*(j - i)。

     如果ai <= aj,则对于k < j,有Aik = min(ai, ak) * (k - i)。由于(k - i) < (j - i),min(ai, ak) <= min(ai, aj) ,所以Aik < Aij. 这说明,j没必要往左移,这是只能让i往右移。

     如果ai > aj,则对于k < i,有Aik = min(ak, aj) * (j - k)。由于(j - k) < (j - i),min(ak, aj) <= min(ai, aj) ,所以Aik < Aij. 这说明,i没必要往右移,这是只能让j往左移。

package area;

public class ContainerWithMostWater {

    public int maxArea(int[] height) {
        int n = height.length;
        int maxArea = 0;
        int i = 0;
        int j = n - 1;
        while (i < j) {
            int area = Math.min(height[i], height[j]) * (j - i);
            if (height[i] <= height[j]) 
                ++i;
            else 
                --j;            
            
            if (area > maxArea)
                maxArea = area;
        }
        
        return maxArea;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

 

LeetCode - Container With Most Water

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5047844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!