leetcode—Container With Most Water

来源:互联网 发布:鹏业填报软件 编辑:程序博客网 时间:2024/06/08 00:53

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 and n is at least 2.

class Solution {    public int maxArea(int[] height) {        if(height==null || height.length<=0) return 0;        int index1 = 0;        int index2 = height.length-1;        int max = 0;        while(index1<index2){            max = Math.max(max,Math.min(height[index1],height[index2])*(index2-index1));            if(height[index1]<height[index2]){                index1++;            }else{                index2--;            }        }        return max;    }}

和Two sum类似,利用夹逼准则,起始条件是一个索引在数组最左边,另外一个索引在数组最右边,从两边向中间靠拢,前进的准则是两个索引对应的数组值,如果左边的比较小,那么左边的像右滑动,如果右边的比较小,右边的像左滑动,因为这个装水是利用的短板原理,如果左边的比较小,滑动他,有可能会变大,但是滑动右边的,一定会变小,因为不是横坐标变小了就是纵坐标变小