盛最多水的容器(Container With Most Water)-java解法
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
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.
示例 1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
java解法
1.暴力解法
每次固定住一边,另一边从左向右遍历。两边中更短的为高,两边的距离为底。依次计算出curArea,并与maxArea比较。
代码:
class Solution {
public int maxArea(int[] height) {
int maxRes = 0;
int n = height.length;
for(int i =0;i<n-1;i++){
for(int j =i+1;j<n;j++){
int h = height[i]<height[j]? height[i]:height[j];
int curArea = (j-i)*h;
maxRes = maxRes>curArea? maxRes:curArea;
}
}return maxRes;
}
}
2.双指针法
如下图所示,在一开始,我们考虑相距最远的两个柱子所能容纳水的面积。水的宽度是两根柱子之间的距离 d = 8d=8;水的高度取决于两根柱子之间较短的那个,即左边柱子的高度 h = 3h=3。水的面积就是 3 \times 8 = 243×8=24。
如果选择固定一根柱子,另外一根变化,水的面积会有什么变化吗?稍加思考可得:
当前柱子是最两侧的柱子,水的宽度 dd 为最大,其他的组合,水的宽度都比这个小。
左边柱子较短,决定了水的高度为 3。如果移动左边的柱子,新的水面高度不确定,一定不会超过右边的柱子高度 7。
如果移动右边的柱子,新的水面高度一定不会超过左边的柱子高度 3,也就是不会超过现在的水面高度。
由此可见,如果固定左边的柱子,移动右边的柱子,那么水的高度一定不会增加,且宽度一定减少,所以水的面积一定减少。这个时候,左边的柱子和任意一个其他柱子的组合,其实都可以排除了。也就是我们可以排除掉左边的柱子了。
这个排除掉左边柱子的操作,就是双指针代码里的 i++。i 和 j 两个指针中间的区域都是还未排除掉的区域。随着不断的排除,i 和 j 都会往中间移动。当 i 和 j 相遇,算法就结束了。
来源:nettee
链接:https://leetcode-cn.com/problems/container-with-most-water/solution/on-shuang-zhi-zhen-jie-fa-li-jie-zheng-que-xing-tu/
代码:
class Solution {
public int maxArea(int[] height) {
int i =0;
int j = height.length-1;
int res = 0;
while(i<j){
int h = height[i]>height[j]? height[j]:height[i];
int curArea = (j-i)*h;
res = res>curArea? res : curArea;
if(height[i]>height[j]){
j--;
}else{
i++;
}
}return res;
}
}