题目
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.
解题思路
这道题如果允许在
O(n2)
的时间内完成的话,直接运用两重循环和“打擂台”算法即可求得正确答案。但是,要在
O(n)
的时间内找到正确答案,就变成了两个指针问题。要使容器的面积最大,宽度和高度都应该达到最大,因此可以设置两个指针并初始化为 i = 0
和 j = height.length - 1
,先从宽度最大开始,然后 i
和 j
分别向中间扫描。在向中间扫描过程中,宽度在不断缩小,因此,要使容器的面积增大,容器的高度 必须增大,所以一直扫描找到新的大于原来的 容器高度 的数字时停止扫描,计算新的面积并与原来的面积进行比较。(注意 容器的高度 取的是两条 lines 中高度较小的 line 的高度,因此每次向中间扫描时,如果是 height[i] < height[j]
,则只需指针 i
进行移动寻找新的更高的高度即可,而 j
不需要移动,反之则 j
移动,i
不移动,这样就不会漏解了。)
Java代码实现
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1;
int area = 0;
int h = 0;
while (i < j) {
h = Math.min(height[i], height[j]);
int newArea = h * (j - i);
area = Math.max(area, newArea);
// 注意仅当 height[i] == height[j]时,下面两条语句才会一起执行,i和j一起向中间移动
// 否则,只有值比较小的那个指针会向中间移动,以找到比容器原来的高度更高的值
while (i < j && height[i] <= h) { ++i; }
while (i < j && height[j] <= h) { --j; }
}
return area;
}
}