题目:
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.
分析与解答:
n个数,a1到an,每个数代表一个坐标(i,ai),将每个数与各自的(0,ai)坐标相连形成一条垂直于X轴的直线。在这些直线里挑两条,形成一个容器,让这个容器在不倾斜的情况下能装最多的水。
容器的装水量取决于两个因素,一个是两个边最小的那一个的高度,另一个是两个边之间的距离。由于数组是无序的,所以高度是没有规律的因素,必须一个一个遍历,但边的距离是有规律的,所以可以设立头尾两个指针head和end,记下他们的装水量V和边的高度h1,h2,假设h1<=h2。之后往中间进行移动,如果移动较高的那条边,是不可能增加装水量的。所以只能移动较矮的那条边。移动过程中如果碰到比h1还矮的边,也是无法增加装水量的,直到遇到比h1高的边,此时重新计算装水量,如果比V大,则刷新h1,h2;否则继续移动,直到head和end相遇。
class Solution {
public:
int maxArea(vector<int> &height) {
int left = 0, maxArea = 0, right = height.size() - 1;
while (left < right) {
maxArea = max(maxArea,
(right - left) * min(height[left], height[right]));
if (height[left] < height[right])
left++;
else
right--;
}
return maxArea;
}
};