您的位置:首页 > 大数据 > 人工智能

Container With Most Water

2013-11-30 10:08 141 查看
public int maxArea(int[] height) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int i = 0;
int j = height.length-1;
int max=0,temp =0;

while(i<j){
temp = (j-i)*(height[i]>height[j]?height[j]:height[i]);
if(temp>max){
max = temp;
}
if(height[i]<height[j]){
i++;
}else{
j--;
}
}
return max;
}
设置两个指针,从两头往中间靠拢,如果右边高,则保留右边,左边加1,;左边高,则保留左边,右边减1

证明:不管是左边加1还是右边减1,容器在x轴上的长度都减少了。一次计算完后,这时,有两个选择,要么左边加1,要么右边减1
如何选择,就看左边高还是右边高了。为什么要保留高的?
设a<b,a=height[i],b=height[j],c=height[i+1],d=height[j-1];
在移动指针之前,maxArea=(j-i)*a;
假设移动左边的指针,则maxArea1=(j-i-1)*min(c,b),有可能大于maxArea
如果移动右边的指针,则maxArea2=(j-i-1)*min(a,d)<maxArea=(j-i)*a
移动右边的指针,得到的面积肯定比移动指针前小,那就没必要考虑这种情况,所以要移动左边的指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: