11. Container With Most Water

来源:互联网 发布:淘宝哪家supreme复刻 编辑:程序博客网 时间:2024/06/05 08:49

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 linei 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.


解题思路: 设置两个指针,分别指向头和尾,若指针要向内部移动,移动后的指针对应的高度应该大于最低值,这样面积才有增大的可能,因为宽度变窄了,只能高度提升.即最终的范围其两侧不能有高于其高度的项存在.

时间复杂度:O(N)

空间复杂度:O(1)

 public int maxArea(int[] height) {        if(height==null||height.length==1)            return 0;        int i=0,j=height.length-1;        int max=0;        int temp,k;        while(i<j){            temp=height[i]<height[j]?height[i]:height[j];            if(temp*(j-i)>max)                max=temp*(j-i);            if(height[i]<height[j]){                for(k=i+1;k<j;k++){                    if(height[k]>height[i]){                        i=k;                        break;                    }                }                if(k==j)                    return max;            }else{                for(k=j-1;k>i;k--){                    if(height[k]>height[j]){                        j=k;                        break;                    }                }                if(k==i)                    return max;            }           }        return max;            }


0 0