leetcode[Container With Most Water]

来源:互联网 发布:文泰2009端口设置 编辑:程序博客网 时间:2024/06/05 20:48

错误解法(遇到很大的数组时无法通过,会超时):

class Solution {//这个题的目的是找到两条线段,这两条线段和彼此之间相交的x轴的长度形成一个竖直(因为要求这个容器不允许倾斜)的容器,计算这个容器可以装多少水//那么就是利用木桶原理(因为这个容器不允许倾斜),然后用最短的线段做容器的高    public int maxArea(int[] height) {        int max = 0;        for(int i = 0; i < height.length; i++){        if(height[i] == 0)//若高度为0,则(i,height[i])到(i,0)并没有形成一条直线,只是一个点,所以要跳过这个情况        continue;        for(int j = i + 1; j < height.length; j++){        if(height[j] == 0)//若高度为0,则(i,height[j])到(i,0)并没有形成一条直线,只是一个点,所以要跳过这个情况        continue;        int h = Math.min(height[i], height[j]);        int l = j - i;        max = Math.max(max, l*h);        }        }                return max;    }}

解法一:

class Solution {//这个题的目的是找到两条线段,这两条线段和彼此之间相交的x轴的长度形成一个竖直(因为要求这个容器不允许倾斜)的容器,计算这个容器可以装多少水//那么就是利用木桶原理(因为这个容器不允许倾斜),然后用最短的线段做容器的高//因为要用到相隔距离,所以不能对原数组排序//用上面的错误解法思路很清晰,可以遍历完所有可能构成的木桶,但会超时//下面介绍另一种可以求解的思路/*    1、The widest container (using first and last line) is a good candidate, because of its width.        Its water level is the height of the smaller one of first and last line.    2、All other containers are less wide and thus would need a higher water level in order to hold more water.    3、The smaller one of first and last line doesn't support a higher water level        and can thus be safely removed from further consideration. */    public int maxArea(int[] height) {    int left = 0, right = height.length - 1;    int max = 0;    while(left < right){    int h = Math.min(height[left], height[right]);    int l = right - left;    max = Math.max(max, l * h);    //下面这个就是尽可能让短的那块木板变长,因为不管怎样往下走的时候底边会缩短,我们能做的就是让高变长    if(height[left] < height[right])//左边更短,就让左边移动,希望下次的height可以高一点    left++;            else//右边更短,就让右边移动,希望下次的height可以高一点            right--;    }        return max;    }}


原创粉丝点击