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.
题目大意:(i,ai)表示在位置i线的高度,求两条线中间最大的存水量(假设为存水)。根据木桶原理,容量=最矮的高度*距离
方法:不能用穷举法,时间复杂度太高。两边分别设置一个指针,一左一右逐渐向中间移动指针。比较两个指针高度,高度小的向中间移动,比较移动后和移动前容量大小,得到最大存水量。
public class Solution {
public int maxArea(int[] h) {
if(h==null || h.length==0) return 0;
int left=0,right=h.length-1;
int area=0;
while(left<right){
area=Math.max(area,(right-left)*Math.min(h[left],h[right]));//获取最大容量
if(h[right]>h[left]){
left++;
}else{
right--;
}
}
return area;
}
}