题目链接
题目描述
实现代码
思想:首先分析问题,对于一个数组nums[n],如果取其两端i 和 j,那么能够盛的水容量为:
Math.min(nums[i], nums[j]) * (j-i)
因此,可以采取双指针的思想,每次移动两端值最小的位置,直到两个指针相遇,实现代码如下:
class Solution {
public int maxArea(int[] height) {
int len = height.length;
if(len == 2) {
return Math.min(height[0], height[1]);
}
int pl = 0;
int pr = len - 1;
int result = Math.min(height[pl], height[pr]) * (len-1);
while (pl < pr) {
if(height[pl] > height[pr]) {
pr--;
} else {
pl++;
}
int current = Math.min(height[pl], height[pr]) * (pr - pl);
if(result < current) {
result = current;
}
}
return result;
}
}