盛⽔最多的容器
算法思想:对撞指针:
我写的代码:
class Solution {
public int maxArea(int[] height) {
int left=0;
int right=height.length-1;
int minHight=-1;//防止[2,0]这种特殊情况
int maxV=0;
while(left<right) {
if(height[left]>height[right]&&height[right]>minHight) {
maxV=Math.max(maxV,height[right]*(right-left));
right--;
} else {
maxV=Math.max(maxV,height[left]*(right-left));
left++;
}
}
return maxV;
}
}
官方题解:
class Solution
{
public int maxArea(int[] height)
{
int left = 0, right = height.length - 1, ret = 0;
while(left < right)
{
int v = Math.min(height[left], height[right]) * (right - left);
ret = Math.max(ret, v);
if(height[left] < height[right]) left++;
else right--;
}
return ret;
}
}