1.题目描述
英文版:
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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case,
the max area of water (blue section) the container can contain is 49.Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
中文版:
给n个非负整数a1,a2,a3.....,an,他们可以用坐标表示为(i,ai)。
绘制n条垂直线,线i的两个端点位于(i,ai)和(i,0)。
寻找两条线,使他们与x轴组成一个容器,
并且这个容器能够装最多的水。
注意:你不能倾斜容器,并且n大于等于2。
以上的垂直线代表数组[1,8,6,2,5,4,8,3,7],在这个例子中,容器能装最大面积的水为49.
例子:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
2.解法
2.1 解法1
思路:
当看到这道题的时候,第一反应就是使用暴力法破解。双重循环遍历所有值进行两两相加,保存最大的那个值并返回。但是时间复杂度非常的高,可以看在LeetCode上运行的结果图。
public static int maxArea1(int[] array) { int maxArea = 0; for(int i = 0;i < array.length;i++){ for(int j = i+1;j < array.length;j++){ int currentArea = (j - i) * Math.min(array[i],array[j]); if(currentArea > maxArea){ maxArea = currentArea; } } } return maxArea; }
在LeetCode上运行的结果:
2.2 解法2
思路:
这种解法是使用两个指针进行破解,第一个指针i从0开始往后遍历,第二个指针j从array.length - 1开始往前遍历。如果第i个数小于j个数,则i继续往后移;
如果第i个数大于第j个数,则j继续往前移。在移动的过程中不断的刷新最大值,最后返回。
代码实现:
public static int maxArea2(int[] array) { int i = 0; int j = array.length - 1; int maxArea = 0; while (i < j){ maxArea = Math.max(maxArea,(j - i) * Math.min(array[i],array[j])); if(array[i] < array[j]){ i++; }else { j--; } } return maxArea; }
在LeetCode上运行的结果:
2.3 解法3
思路:
这种解法是在解法2的基础上稍微进行了一点优化。如果i在移动的过程中,第i个数与Math.min(array[i],array[j])相等,则继续往后移;
如果j在移动的过程中,第j个数与Math.min(array[i],array[j])相等,则继续往后移;
代码实现:
public static int maxArea3(int[] array) { int i = 0; int j = array.length - 1; int maxArea = 0; while (i < j){ int h = Math.min(array[i],array[j]); maxArea = Math.max(maxArea,(j - i) * h); while (i < j && array[i] == h) i++; while (i < j && array[j] == h) j--; } return maxArea; }
在LeetCode上运行的结果:
3.测试
在本地,我只是简单写了一个main函数来对它进行测试。但是这些代码都是在LeetCode上运行通过了的。
public static void main(String[] args) { int[] array = {1,8,6,2,5,4,8,3,7}; int result = maxArea2(array); System.out.println(result); }
欢迎关注个人公众号,可直接扫描以下二维码或微信搜索“阿毛聊技术”。
来源:https://www.cnblogs.com/limaodeng/p/12318170.html