Container With Most Water

来源:互联网 发布:js打开微信浏览器跳转 编辑:程序博客网 时间:2024/06/18 07:43

问题描述

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.
插图
题目的大意其实就是有一堆竖立着的线段,长短不同,邻近的两个线段距离为1,现在让你挑两个线段,加上x轴围成一个水桶,问容量最大的水桶的容量是多少。

木桶原理

就像大家都知道的那样,水桶盛水的量取决于最短的那一根木板,因此,要尽可能选择相距更远,长短都比较长的两条线段,才能盛最多的水。

愚蠢的方法

像这种找最大的题目,一般都会先想到遍历,算法如下:

public class Solution {    public int maxArea(int[] height) {        int res = 0;        int max = height.length;        for (int i = 0; i < max-1; i++){            for (int j = i+1; j < max; j++){                res = Math.max(res,(j-i)*Math.min(height[i],height[j]));            }        }        return res;    }    }

这种方法就是遍历所有可能的情况,然后找到最大值,其时间复杂度为O(N^2)。其实这种方法很笨很慢,因为做了很多无用的计算。有些情况一看就知道肯定不可能是最大了,根本不用算。

有灵性的方法

我们可以先把两个指针指向最左边和最右边的线段,先把这个最胖的桶的容量给计算出来。如图片中的阴影部分所示。
下一步是把比较短的线段的指针直接内移一格~
无知群众:难道你不怕这条线段和其他的线段组成的桶比一开始的那个大吗?
我:绝对不可能,因为木桶原理,短的线段决定了桶高度的上限,而刚才的线段距离就是宽度的上限,当上限遇上上限,就不再有提升的可能了,所以这条短线段绝对不可能和另外一条线段组成更大的桶。
你看,一下减少了N-1次计算。
而另外一条长线段,它其实是被短线段拖了后腿,它存在和别的线段组成更大桶的可能性,当然某一天如果它遇到了比自己更长的线段,它的指针也要内移。
可以看出,这种方法运行时间是和线段个数线性相关的,复杂度为O(N)。
代码如下:

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

就觉得自己很帅。