leetcode Container with most Water

来源:互联网 发布:淘宝店铺号和旺旺号 编辑:程序博客网 时间:2024/06/10 15:39

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

首先理解题意,求的是两条纵线和x轴组成的容器所能装水的最大容积(面积),即求max(min(ai,aj)*(j-i)),其中j>i,这道题首先需要证明一个理论,其实这个理论从直观观察还是可以看出来的,这里引用博客http://blog.csdn.net/a83610312/article/details/8548519里的证明,写的比较简洁清晰:

①: 在 j 的右端没有一条线会比它高! 假设存在 k |( j<k && ak > aj) ,那么  由 ak> aj,所以 min( ai,aj, ak) =min(ai,aj) ,所以由i, k构成的容器的容积C' = min(ai,aj ) * ( k-i) > C,与C是最值矛盾,所以得证j的后边不会有比它还高的线;

②:同理,在i的左边也不会有比它高的线;

说白了就是我们从两头开始找起往中间收缩,只找比两条边中较小的边高的边,这样得到的容积才有可能比当前的大,代码:

public int maxArea(int[] height) {    int left=0,right=height.length-1;    int area;    int max=0;    while(left<right){        area=Math.min(height[left],height[right])*(right-left);        if(area>max) max=area;        if(height[left]<height[right]){            int k=left+1;            while(k<right&&height[k]<=height[left]) k++;            left=k;        }        else{            int k=right-1;            while(k>left&&height[k]<=height[right]) k--;            right=k;        }    }    return max;}

0 0
原创粉丝点击