<leetcode>Container With Most Water

来源:互联网 发布:淘宝联名信用卡怎么用 编辑:程序博客网 时间:2024/05/21 08: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.

一开始想的是两个for循环遍历所有的组合找出最大值,显然不满足时间。

后来想到2个pointer靠拢的方法。container容积的定义是最小边*底边,所以从底边最大的情况开始考虑。当缩小底边,需要其中最小边变大,因此从low和high两个边里找到比较小的,并移动,直到找到一个比之前大的边,然后计算当前的容积并继续移动小边。当low>=high之后结束,然后返回最大的容积


public class Solution {    public int maxArea(int[] height) {        int max=(height.length-1)*minimum(height[0],height[height.length-1]);        int minLine=minimum(height[0],height[height.length-1]);        int low=0;        int high=height.length-1;        while(low<high){            if(height[low]<height[high]){                minLine=height[low];                while(low<high&&height[low]<=minLine){                    low++;                }                if(low<high){                    minLine=minimum(height[low],height[high]);                    if((high-low)*minLine>max){                        max=(high-low)*minLine;                    }                }            }            else if(height[low]>=height[high]){                minLine=height[high];                while(low<high&&height[high]<=minLine){                    high--;                }                if(low<high){                    minLine=minimum(height[low],height[high]);                    if((high-low)*minLine>max){                        max=(high-low)*minLine;                    }                }            }        }        return max;    }    public int minimum(int a, int b){        if(a<=b){            return a;        }        else return b;    }}


0 0
原创粉丝点击