如何盛最大的水?
数组代表高度, 盛的水量V= min( height[left] 、 height[right] ) * 底部的长度= [right- left]
双指针解决这个问题, 从左边、右边不断逼近, 逐渐取得最大值,
如何进行更新, 不断进行更新逼近,因为决定的是height[left]、height[right],中的最小值, 所以当,对right 和height 采用快速排序中不断毕竟的原则
答案是有,用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。
英文解释该中情况
Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don’t support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left.
快速排序
class Solution {
public int maxArea(int[] heights) {
int result=0;
int n = heights.length;
int left=0, right =n-1;
while(left<right){
int tmp= (right-left) * Math.min(heights[left],heights[right]);
result = Math.max(tmp,result);
if(heights[left]<heights[right])
{
++left;
}
else
{
--right;
}
}
return result;
}
}
如何进行改进
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while (i < j) {
int h = min(height[i], height[j]);
water = max(water, (j - i) * h);
//i<j 必须满足该中情况, 类似快速排序
while (height[i] <= h && i < j) i++;
while (height[j] <= h && i < j) j--;
}
return water;
}