[LeetCode]11. Container With Most Water

Description:


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

——————————————————————————————————————————————————————————

Solution:

一开始我的思路是朴素的双重循环算法,结果TLE了(这里就不贴代码了)。

后来实在想不到如何简化算法,降低时间复杂度,就去翻了翻solution,被整洁精悍的"标答"惊艳到了:

[LeetCode]11. Container With Most Water

标答的思路是:能装多少水取决于,两垂直边较短的一边有多长,以及两边之间的间隔有多长。那么,在给定的a1,a2,...,an的数组上,最长的距离是从a1到an的,因此现在只需要比较a1和an哪个的height更短,用较短的一边*两边间隔即所求面积。下一步将a1和an中较短的一边向中间挪一位,即比如an更短,那么此时就将a1与an-1作比较...以此类推,时间复杂度只需要O(n)。标答的思路和二分查找法有点类似,只是一个从中间向两边扩散,一个从两边向中间扩散。

这道题给我的启示是不能用固化思维(二重循环结构一一比较)思考问题,应该思考怎样对题目进行数学建模,抽象化思考。

(ps:在left++还是right--的比较上我错误地用left和right,即下标做比较导致WA,实际应该是height[left]和height[right]比较,低级错误引以为戒)