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.
在二维坐标系里,有一组长短不一垂直线段,用(i, ai)来表示每一条线,用任意两条线段和 x 轴可以组成一个容器,求容量最大的容器的容积。
简单的做法是采用二重循环遍历所有组合保利求解,找出最大的容器,但是这样做会导致超时。
更为合理的解法是,用两个指针分别指向数组的两端,当左边指针指向的数大于右边时,右边指针左移;当右边大于左边时,左边指针右移。重复此操作指导左边指针与右边指针会和。在遍历的过程中保存每次的容器容积,最后返回最大值即可。
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size() - 1;
int v = 0, max = 0;;
while (l < r) {
v = min(height[l], height[r]) * (r - l);
if (v > max) {
max = v;
}
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return max;
}
};