题目

题解一:双指针法
思路:
题目中的示例为:

在初始时,左右指针分别指向数组的左右两端,它们可以容纳的水量为 min(1,7)∗8=8
此时我们需要移动一个指针。移动哪一个呢?应该移动对应数字较小的那个指针(即此时的左指针)。这是因为,由于容纳的水量是由
所以,我们将左指针向右移动:

此时可以容纳的水量为 min(8,7)∗7=49。由于右指针对应的数字较小,我们移动右指针:

此时可以容纳的水量为 min(8,3)∗6=18,由于右指针对应的数字较小,我们移动右指针:

此时可以容纳的水量为 min(8,8)∗5=40,两指针对应的数字相同,我们可以任意移动一个,例如左指针:

最后左指针大于右指针的时候,就是循环结束的条件
动图可以参考:盛最多水的容器
代码:
java
class Solution {
public int maxArea(int[] height) {
//解法:双指针法
int pre = 0;
int bef = height.length-1;
//记录每次计算的最大面积
int maxeare = 0;
while(pre < bef){
int crueare = (Math.min(height[pre],height[bef]))*(bef - pre);//记录此刻的两个指针向的区域的面积
maxeare = Math.max(crueare,maxeare);//刷新最大面积
//让指向小的数,移动指针;
if(height[pre]<height[bef])
pre = pre + 1;
else
bef = bef - 1;
}
return maxeare;
}
}