天天看点

[LeetCode] Container With Most Water 装最多水的容器

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 解法二: