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

这道题開始看了好半天都没看明确是什么意思。

最后发现题目的意思是给定n条线段,第i条线段的两个端点是(i,0)和(i,ai),能够发现这n条线段都是垂直于x轴的,选取当中的两条线段,使这两条线段和x轴构成的容器能容纳的水最多。

随意两个线段(下标索引各自是i和j,如果i<j)能容纳的水量是(j-i)*min(ai,aj)。

假设不考虑时间复杂度,使用双层循环能够计算出随意两条线段之间能容纳的水量,这样能够计算出两条线段之间能容纳的水量的最大值。

时间复杂度是O(n^2)。可是明显这样的解法有点慘不忍睹。终于也没想出更好的解法,查看了Discuss,时间复杂度是O(n)的解法。

非常巧妙的一个解法。如果先选取的是两端之间的两条线段。这样这两条线段之间的距离是最大的,长度是给定数组的长度减1。那么在这样的情况下要容纳很多其它的水。因为宽度已经是最大的了,仅仅能想法提高线段的高度,这样的情况下如果两端是左边比右边高,那么仅仅有可能是将左边的指针右移,否则将右边的指针左移,然后这右回到了初始的问题。这样不断移动下去到左右指针相等为止,代码非常easy。以下以输入[1,2,4,3]为例:


runtime:28ms

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


原文地址:https://www.cnblogs.com/clnchanpin/p/6792980.html