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.app

分析:这道题与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。代码以下:spa

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;
    }
};
相关文章
相关标签/搜索