11. Container With Most Water 容器最大水容量

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.

Note: You may not slant the container and n is at least 2.

Example:

1
2
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
暴力破解
双指针法

本质上就是求容量的大小问题。使用左右指针从两边向中间扫描,扫描的时候计算出当前指针位置上的容器体积并和之前最大的容器体积进行比较,取最大的容器体积。计算体积的告诉是由两边最低的高度所决定的。最后输出容器体积的最大结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int left = 0;
int right = height.length - 1;

while(left < right){
maxArea = Math.max(maxArea,Math.min(height[left],height[right]) * (right - left));
if(height[left] < height[right]){
left ++;
} else{
right --;
}
}
return maxArea;
}
}

文章作者: 彭峰
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 彭峰 !
 上一篇
2021-05-02 彭峰
下一篇 
2021-05-02 彭峰
  目录