算法描述
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.
注意: You may not slant the container and n is at least 2.
算法一实现:
public class Solution {
/**
* Given n non-negative integers a1, a2, ..., an, where each represents<br>
* a point at coordinate (i, ai). n vertical lines are drawn such that<br>
* the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,<br>
* which together with x-axis forms a container, such that the container <br>
* contains the most water.<br>
* <font color="red">Note: You may not slant the container and n is at least 2.</font>
* @param height int[]
* @return maxArea int
*/
public int maxArea(int[] height) {
//height不能为空
if (height == null) {
throw new NullPointerException("height数组不能为空");
}
//数组元素为两个
if (height.length == 2) {
if (height[0] == 0 || height[1] == 0) return 0;
else if (height[0] < height[1]) return height[0];
else if (height[0] >= height[1]) return height[1];
}
//数组元素超过两个
if (height.length > 2) {
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
if (height[i] == 0) {
continue;
}
int area = 0;
for (int j = i + 1; j < height.length; j++) {
if (height[j] == 0) {
continue;
}
int areaTemp = 0;
if (height[i] < height[j]) {
areaTemp = height[i] * (j - i);
} else {
areaTemp = height[j] * (j - i);
}
if (area < areaTemp) {
area = areaTemp;
}
}
if (maxArea < area) {
maxArea = area;
}
}
return maxArea;
}
//数组元素个数小于2时,值为0
return 0;
}
}
缺点:算法时间复杂度高,效率低。
算法二实现(优化)
public class Solution {
public int maxArea(int[] height) {
//height不能为空
if (height == null) {
throw new NullPointerException("height数组不能为空");
}
//数组个数不小于2时
if (height.length >= 2) {
int maxArea = 0;
int i = 0;
int j = height.length - 1;
while (i != j) {
int area = 0;
if (height[i] < height[j]) {
area = height[i] * (j - i);
i++;
} else {
area = height[j] * (j - i);
j--;
}
if (maxArea < area) {
maxArea = area;
}
}
return maxArea;
}
//数组元素个数小于2时,值为0
return 0;
}
}
变成for循环
public int maxArea(int[] height) {
//height不能为空
if (height == null) {
throw new NullPointerException("height数组不能为空");
}
//数组个数不小于2时
if (height.length >= 2) {
int maxArea = 0;
for (int i = 0, j = height.length - 1, area = 0; i != j; ) {
if (height[i] < height[j]) {
area = height[i] * (j - i);
i++;
} else {
area = height[j] * (j - i);
j--;
}
if (maxArea < area) {
maxArea = area;
}
}
return maxArea;
}
//数组元素个数小于2时,值为0
return 0;
}
算法二证明:
在a1,a2.....an中,存在两个点使所求面积最大,所以假设ax,ay为其中使面积最大的两个点,i < j。我们需要证明的是一定能遍历到这两个点即可。i从左到右移动,j从右往左。i和j对应的值哪个小哪个移动,这样始终在找大值,越移动j - i越来越小,高度越来越大,所以一定能找到ax和ay。
再具体证明一下,如下图所示:
图1
我们需要证明两点:一.要想使ax和ay所在面积最大,a(y+1)的值一定是1或2的位置(即:比ax小的位置);二:如何保证a(y+1)移动到a(y)。
i当前在ax的位置,j当前在a(y+1)的位置。当j向左移动后,j-i变小了,如果想使ax和ay所在面积最大,只能是a(y+1)的值在1和2的位置;要使j向左移动,则只要height[i] > height[j]。所以一定可以移动到ay的位置,证明完成。