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

Leetcode 11 Container With Most Water

2015-07-25 10:23 393 查看

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.

Solution1

这道题实际上是找到两根线,使得两根线之间能聚集的雨水最多,这和42题不一样。这里的思路是从数组两端开始,计算一次两根线之间能聚集多少雨水,完了将较短的那条边移动一格(移动方向是前面的指针往后移,后面的指针往前移),重新计算两根线之间能聚集多少雨水。

public class Solution {
public int maxArea(int[] height) {
int result = 0;
int n = height.length;
for(int i=0,j=n-1;i<j;){
result = Math.max(result,Math.min(height[i],height[j])*(j-i));
if(height[i]<height[j]) i++;
else j--;
}
return result;
}
}


Solution2

解法一比较直观易懂,但实际上计算了很多次不必要的迭代。因为当两根线往中间靠拢的时候,每次都是选择的最短那条边往中间移动,对于那些移动后比移动之前还要短的边实际上可以不需要考虑,只需要考虑移动后比移动前高的边就行,因为往中间移动的时候宽变窄了,只有较短的边变高之后才有可能使得整个的矩形面积最大。这种思路的代码如下:

int result = 0;
int n = height.length;
for(int i=0,j=n-1;i<j;){
result = Math.max(result,Math.min(height[i],height[j])*(j-i));
if(height[i]<height[j]){
int k = i+1;
while(k<j&&height[k]<=height[i]) k++;//将较短边往中间移动,知道找到一个比现有边更高的边
i = k;
}
else{
int k = j-1;
while(k>i&&height[k]<height[j]) k--;
j = k;
}
}
return result;


Solution3

解法2在运行的时候比解法1更加高效,但是代码却没有解法一那么直白浅显。这里有一种不一样的代码实现,思想仍然是一样的。

public class Solution {
public int maxArea(int[] height) {
int result = 0;
for(int i=0,j=height.length-1;i<j;){
int h = Math.min(height[i],height[j]);//先找到最短的边
result = Math.max(result,h*(j-i));
while(i<j&&height[i]<=h) i++;//虽然有两个while循环,实际每次迭代的时候都只有最短边在移动直到比当前边高
while(i<j&&height[j]<=h) j--;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode