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

LeetCode_Container With Most Water

2015-05-02 16:57 330 查看


Container With Most Water

 

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.
题目:输入一个整形数组,如a=[ 2,4,6,3,5 ],数字的大小为挡板的高度,两两数字的间距为挡板的间距,比如4和3两个挡板之间的水容量就是两个数字之差乘以两数字的间距,即(4-3)*(3-1)= 2,假设两个数字在该数组中的序号为i,j(i<j),那么总结计算公式就是:(j - i)*(min(a[ i ],a[ j ]))。
题目清楚之后,开始考虑,如果两次遍历是可以求出来的,但是时间复杂度O(n^2)太大。另一种方法,假设已经找出了这两个挡板i和j(i<j),那么在i的左边的所有数字都小于i,在j的右边的所有数字都小于j,反证法可以证明。那么就从数组两端开始向中间靠近,每次选取两个数字较小的一个向中间靠近(为什么选较小的一个呢,假如选了较大的一个来处理,即使下一个比较大的那个还要大,但是由以上计算公式得,min(a[
i ],a[ j ])还是较小的那个挡板,并且(j - i)更小了,所以一定是选择较小的那个挡板向中间靠拢,并且直到找到比较小的那个数字大的一个数字),这样线性复杂度内就可以解题了。
java解题:
public static int maxArea(int[] height) {
int i=0,j=height.length-1,temp=0,max=0;
while(i<j){
max=Math.max(max, (j-i)*Math.min(height[i],height[j]));
if(height[i]<height[j]){
temp = i;
while(temp<j && height[temp]<=height[i])
temp++;
i=temp;
}
else{
temp = j;
while(i<temp && height[temp]<=height[j])
temp--;
j=temp;
}
}
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息