您的位置:首页 > 编程语言 > Java开发

leetcode解题之 11. Container With Most Water Java版(最大盛水容积)

2017-04-06 15:13 405 查看

11. 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.

找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水。

假设先选取的是两端之间的两条线段,这样这两条线段之间的距离是最大的,长度是给定数组的长度减1。那么在这种情况下要容纳更多的水,由于宽度已经是最大的了,只能想法提高线段的高度,这种情况下如果两端是左边比右边高,那么只有可能是将左边的指针右移,否则将右边的指针左移,然后这右回到了初始的问题,这样不断移动下去到左右指针相等为止

// leetcode此种方法有时TLE,有时AC
public int maxArea1(int[] height) {
if (height == null || height.length == 0)
return 0;
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(Math.min(height[left],
height[right]) * (right - left), maxArea);
if (height[left] <= height[right])
left++;
else
right--;

}
return maxArea;
}

// 优化版
public int maxArea(int[] height) {
if (height == null || height.length == 0)
return 0;
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
// 设算当前的最大值
maxArea = Math.max(Math.min(height[left],
height[right]) * (right - left), maxArea);
if (height[left] <= height[right]) {
int k = left;
// 如果letf右边的高度比left的高度小,面积不可能比之前大,所以
// 从[left, right - 1]中,从左向右找,
//找第一个高度比height[left]高的位置
while (k < right && height[k] <= height[left])
k++;
left = k;
} else {
int k = right;
// 如果right左边的高度比right的高度小,面积不可能比之前大,所以
// 从[left + 1, right]中,从右向左找,
//找第一个高度比height[right]高的位置
while (k > left && height[k] <= height[right])
k--;
// 从[left, right - 1]中,记录第一个比原来height[right]高的位置
right = k;
}
}
return maxArea;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息