0%

11.盛最多水的容器

双指针

容器的面积由两部分决定,一部分是两条线之间的宽度,另一部分是两条线中较短的那一条,因为水位只能由短板决定。

因此可以让两个指针分别指向数组两端,先计算当前容器面积。之后为了尝试得到更大的答案,应当移动较短的那一侧。因为如果移动较高的一侧,宽度一定变小,而短板仍然可能还是原来那根较短的线,这样面积不可能变得更大;只有移动短板,才有机会找到更高的边,从而弥补宽度缩小带来的损失。

时间复杂度 $O(n)$

空间复杂度 $O(1)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int ans = 0;
while (left < right) {
int high = Math.min(height[left], height[right]);
ans = Math.max(ans, (right - left) * high);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return ans;
}
}