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

leetcode—Container With Most Water

2017-12-19 19:37 369 查看
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

class Solution {
public int maxArea(int[] height) {
if(height==null || height.length<=0) return 0;
int index1 = 0;
int index2 = height.length-1;
int max = 0;
while(index1<index2){
max = Math.max(max,Math.min(height[index1],height[index2])*(index2-index1));
if(height[index1]<height[index2]){
index1++;
}else{
index2--;
}
}
return max;
}
}


和Two sum类似,利用夹逼准则,起始条件是一个索引在数组最左边,另外一个索引在数组最右边,从两边向中间靠拢,前进的准则是两个索引对应的数组值,如果左边的比较小,那么左边的像右滑动,如果右边的比较小,右边的像左滑动,因为这个装水是利用的短板原理,如果左边的比较小,滑动他,有可能会变大,但是滑动右边的,一定会变小,因为不是横坐标变小了就是纵坐标变小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: