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:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
暴力破解
双指针法
本质上就是求容量的大小问题。使用左右指针从两边向中间扫描,扫描的时候计算出当前指针位置上的容器体积并和之前最大的容器体积进行比较,取最大的容器体积。计算体积的告诉是由两边最低的高度所决定的。最后输出容器体积的最大结果。
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;
}
}