原题链接:https://leetcode.com/problems/container-with-most-water/
1. 题目介绍
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.
给出n个非负整数 a1,a2,… ,an,这些数代表了位于坐标(i,ai)处的点。从(i, 0)到(i, ai)做垂线,一共有n条这样的垂线。从这n条线中,选择两个垂线。这两条垂线和X轴形成了一个容器,为了让容器盛更多的水,需要选取最合适的两条的垂线,使得容器的容积最大。
注意:
不可以倾斜这个容器,n最小为2。
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
上述垂线的表示方法是数组 [1,8,6,2,5,4,8,3,7]。在这种情况下,最大容积为49
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
2. 解题思路
双指针法
本题的解题思路是双指针法。设置左边的指针left,初始位置为0,设置右边的指针right,初始位置为数组最后一个元素处。
选取height[left],height[right]中较小的一个作为高,right-left作为底边长度。因此容器的容积为:
m
i
n
(
h
e
i
g
h
t
[
l
e
f
t
]
,
h
e
i
g
h
t
[
r
i
g
h
t
]
)
∗
(
r
i
g
h
t
−
l
e
f
t
)
min(height[left],height[right])*(right-left)
min(height[left],height[right])∗(right−left)
从上述公式我们可以看出,高度和底边长度是限制容器容量的两个主要因素。
因此,需要记录下来最大的容积,然后将左右指针向中心进一步缩小。如果缩小后的最大容积超过了原来的最大容积,那么就更新最大容积的值。
如何将左右指针向中心进一步缩小呢?答案谁的height较小,就改变谁。height[left]较小,left就要右移,height[right]较小,就将right左移。
实现代码
class Solution {
public int maxArea(int[] height) {
int right = height.length-1;
int left = 0;
int max = 0;
while(left < right){
max = Math.max(max, Math.min(height[left],height[right])*(right-left));
if(height[left] < height[right]){
left ++;
}else{
right --;
}
}
return max;
}
}
3. 参考资料
https://leetcode.com/problems/container-with-most-water/solution/