题目链接:Container With Most Water

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.

这道题的要求是给定整形数组a,(i, ai)表示坐标点,这些坐标点向x轴作垂直的线。找到两条线,使其和x轴共同构成的容器,可以装下最多的水。(注意,不允许倾斜容器)

简单直接的思路是两层循环遍历每组可能的情况,时间复杂度O(n2)。可以进一步优化,采用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。

时间复杂度:O(n)

空间复杂度:O(1)

 1 class Solution
 2 {
 3 public:
 4     int maxArea(vector<int> &height)
 5     {
 6         int l = 0, r = height.size() - 1, res = 0;
 7         while(l < r)
 8         {
 9             res = max(res, (r - l) * min(height[l], height[r]));
10             if(height[l] < height[r])
11                 ++ l;
12             else
13                 -- r;
14         }
15         return res;
16     }
17 };