首页 > 其他 > 详细

LeetCode: Container With Most Water

时间:2014-01-26 08:46:49      阅读:397      评论:0      收藏:0      [点我收藏+]

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.

最开始只能想到brute force算法,任意两个配对计算面积,时间复杂度O(n^2)。后来看到一些优化,比如计算以(i, ai)为起点的最大面积时,从数组最后面找,直到可能的最小坐标,maxArea/ai + i; 因为i再小,无论如何无法增加最大面积。

但是依然无法通过。

 

后来看到一种O(n)算法,感觉很高级。有点像双指针思想。原来想的是双指针都是在有序数组上用,发现无序的也可以用。

两个指针,一个指向头,一个指向尾。计算height[start],height[end]中较小的一个,并计算面积,这个面积就是以这个较小的高度为其中较小的一条边,对应的最大面积。

假设固定这条高度较小的边,减小end:如果height[end]>height[start],因为end-start减小了,所以面积小了。如果height[end]<height[start],那么最小高度以及end-start都减小了。

那么现在问题就是,能不能将end增大。。。经过长时间的思考,终于仿佛得到了。。不能增大end。因为end后面的某个值一定是在遇到height[start]之前,遇到了一个比自己大的值,所以才能够移动到下一个位置。

假设height[end‘]<height[start],那么它和之前某个比height[end‘]大的值计算过,这个值一定大于与height[start]的计算结果;

假设height[end‘]>height[start],那么它和之前某个比height[end‘]大的值计算过,这个值也一定大于与height[start]的计算结果。

所以end既不可能增大,也不可能减小。

所以只能改变start++;

LeetCode: Container With Most Water

原文:http://www.cnblogs.com/longhorn/p/3497148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!