Leetcode 11[medium]--Container With Most Water

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.

思路:题意有点难懂。给定一系列的非负整数 a1,a2,...an, 每一个代表相应的坐标的点(i,ai)。经过每个点画垂直于X轴的直线,也就是说 line i 连接 (iai) and (i, 0)。找到其中的两条线,与x轴组成一个容器,满足这个容器可以盛最多的水。 也就是说找到一个方形(正方形或者长方形),由n条线中的两条组成,方形的长由较短的线的高度决定,方形的长由两条线之间的距离也就是x值之差决定,求方形可能的最大面积。

           最开始用双循环的方法,但是所写的code超时了。参考了别人的双指针法,该方法跟以往有些不同,以往是将双指针往有利于找到最大值的方向移动,而这次将短板可以作为移动的判断条件,目的是使 短板更高一些,两个指针分别从首尾向中间缩,哪个板更短,就移动一下。记录下出现的最大面积。

Leetcode 11[medium]--Container With Most Water