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 and n is at least 2.
题目要求:求包含的面积,用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。
时间复杂度:O(n)
Note: You may not slant the container and n is at least 2.
题目要求:求包含的面积,用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public:
int maxArea(vector<int>& height)
{
int left = 0, right = height.size() - 1;
int ret = 0;
while (left < right)
{
int lowhigh = min(height[left], height[right]);
ret = max(ret, lowhigh * (right - left));
if (height[left] == lowhigh)
left ++;
else
right --;
}
return ret;
}
};