Leetcode: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.

分析:这道题与Trapping Rain Water、Largest Rectangle in Histogram有共通之处。解决这三道题,我们都要保持对数字的敏感性,发现隐含在数字后的性质。对于这道题,container装水的量是有短板决定的。可能大家都知道这点,但如何利用这点来完成一个O(n)的算法则值得思考。Brute-force的算法复杂度为O(n^2),但其实在brute-force算法中的很多计算是不必要的,我们大可在计算的过程中将这些不必要(不可能是最优解)的情况prune掉。对于一个高度的line,我们只需求以该line为短板的最大装水量即可,满足最大装水量的container是由该line和离该line最远的且比该line高的line组成。在代码中我们可以用two pointers来实现上述思想。一旦一个line是以短板的角色出现后,我们便可以将其剔除,在后续计算中不考虑以它为边界的container。代码如下:

class Solution {
public:
    int maxArea(vector<int> &height) {
        int result = 0;
        int left = 0, right = height.size()-1;
        
        while(left < right){
            result = max(result, (right-left)*min(height[left], height[right]));
            if(height[left] < height[right])
                left++;
            else right--;
        }
        
        return result;
    }
};

 

posted on 2015-01-15 16:43  Ryan-Xing  阅读(179)  评论(0编辑  收藏  举报