container-with-most-water

题目:

Given n non-negative integers a1 a2 , ..., 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.

这个题目的意思是:(i,0)和(i,ai)构成一条垂直线,i其实是从0到n-1;从n条垂直线中找到两条,与x轴围成一个容器,找出一个容器,装最多的水。

水是平的,所以水的容量就是(k-j)*min(ak,aj)。

最直接的方法就是暴力搜索,时间复杂度为n^2,代码如下:

  int maxArea(int[] height) {
    
        //暴力搜索,时间复杂度为O(n^2) 
        
        int result=0;
        int size = height.length;
        for(int i=0;i<size;i++){
            for(int j=i+1;j<size;j++){
                int area = (j-i)*Math.min(height[i],height[j]);
                if(area>result)result = area;
            }
        }
        return result;
       

但是此方法效率太低。

使用贪心算法 
  1.首先假设我们找到能取最大容积的纵线为 i, j (假定i < j),那么得到的最大容积 C = min( ai , aj ) * ( j- i) ; 
  2.下面我们看这么一条性质: 
  ①: 在 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的左边也不会有比它高的线;这说明什么呢?如果我们目前得到的候选: 设为 x, y两条线(x< y),那么能够得到比它更大容积的新的两条边必然在[x, y]区间内并且 ax’ >= ax , ay’ >= ay; 

可以从两边往中间找,然后去除短板,去除短板是去找更高的板。两边往中间找效果一样,因为每次只移动两边指针的一个,所以还是会遍历到所有情况。但是这样有个好处,就是去短板

这么做的原因在于:从起点和终点开始找,宽度最大,这时每移动一次其中一个点,必然宽度变小。
如此一来,想求最大,只有高度增长才有可能做到,去掉限制----短板(无论向左还是向右移一位,宽度都是减一,所以宽度不变,只需去短板,留长板即可),即放弃高度较小的点。
public class Solution {
    public int maxArea(int[] height) {
        
        int l,r,maxW=0;
        for(l=0,r=height.length-1;l<r;){
            maxW=Math.max((r-l)*Math.min(height[l],height[r]),maxW);
            if(height[l]>height[r])
                r--;
            else
                l++;
        }
        
        return maxW;
    }
}
 
 
原文地址:https://www.cnblogs.com/xiaolovewei/p/8035153.html