LC.P11[盛最多水的容器]

方法一:双指针

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxArea(int[] height) {
int ans = 0, left = 0, right = height.length - 1;
while (left < right) {
ans = Math.max(ans, (right - left) * Math.min(height[left], height[right]));
if (height[left] < height[right]) ++left;
else --right;
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$