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

Leetcode:Container with most water菜鸟解法

2015-02-17 20:34 295 查看
这题想很久啊...一直觉得只能把n*(n-1)/2 种情况全考虑到才能解决

实际上用夹逼方法很容易就可解出来,从最左与最右看,如果左大于右,那怎么动左边都不可能让水增多,所以要移动右边,反之亦然,直到左右相碰

代码如下

class Solution {
public:
int maxArea(vector<int> &height) {
int left =0,result,chang,kuan;
int right = height.size()-1;

chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(kuan == 0) return 0;

result = chang*kuan;
while(left!=right){
if(height[left]<=height[right]){
left++;
}
else right--;
chang = height[left]>height[right]?height[right]:height[left];
kuan = right - left;
if(result<chang*kuan) result = chang*kuan;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 夹逼