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.

给你一个顶点数组,例如{4,7,9},这个定点数组代表直角坐标系上三个点,(1,4),(2,7),(3,9),然后过这三个点,分别作垂直于X轴的线段,例如对于(1,4),线段的两个端点为(1,4)和(1,0),然后,我们可以得到三条垂直于X轴的线段。从这些线段中找出一对组合,使得,这对组合的   横坐标之差  乘以  两条线段中较短者的长度    的乘积最大。

 

解题思路:

 

最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到左边大于右边为止就行了

 

 

先拿最左边的线段和最右边的线段作为组合,计算出乘积,然后,找两者中较为短的一方,慢慢向中间靠拢。举个例子,{4,3,7,2,9,7},先计算4和7的组合的乘积,然后找两者中比较小的一方,这里是4,让它向中间靠拢,向前走一步是3,但3比4小,所以计算3和7的组合是没有意义的,所以,继续向中间靠拢,发现了7,7比4大,所以有可能会得到比原来更大的面积,因此计算7和7的组合的乘积。

重复这个过程,直至左边的工作指针大于等于右边的工作指针

public class Solution {  
  
    public int maxArea(int[] height) {  
        int lpoint = 0, rpoint = height.length - 1;  
        int area = 0;  
        while (lpoint < rpoint) {  
            area = Math.max(area, Math.min(height[lpoint], height[rpoint]) *  
                    (rpoint - lpoint));  
            if (height[lpoint] > height[rpoint])  
                rpoint--;  
            else  
                lpoint++;  
        }  
        return area;  
    }  
}  

 

 

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        size = len(height) # the size of height
        maxm = 0 # record the most water
        j = 0
        k = size - 1
        while j < k:
            if height[j] <= height[k]:
                maxm = max(maxm,height[j] * (k - j))
                j += 1
            else:
                maxm = max(maxm,height[k] * (k - j))
                k -= 1
        return maxm

 

posted @ 2016-03-14 10:58  zxqstrong  阅读(640)  评论(0编辑  收藏  举报