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.
C++ 解法一:
Java 解法一:
這裡需要注意的是,由于Java中的三元運算符A?B:C必須須要有傳回值,是以隻能用if..else..來替換,不知道Java對于三元運算符這麼嚴格的限制的原因是什麼。
下面這種方法是對上面的方法進行了小幅度的優化,對于相同的高度們直接移動i和j就行了,不再進行計算容量了,參見代碼如下:
C++ 解法二:
Java 解法二: