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.
翻译:就是说,x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an。找出两条线段,使他们和x抽围成的面积最大。面积公式是 Min(ai, aj) X |j - i|
Code:
import java.util.HashMap;
import java.util.Map;
/**
*
*/
/**
* @author MohnSnow
* @time 2015年6月2日 下午5:24:20
*
*/
public class LeetCode11 {
/**
* @param argsmengdx
* -fnst
*/
//梯形面积=(上底+下底)*高/2
//Max = (aj+ai)*(j-i)/2
//Time Limit Exceeded---->可见这个空间复杂度有点高,可以尝试利用空间复杂度取代时间复杂度
//一开始没看懂题目,以为是一个梯形了
public static int maxArea(int[] height) {
int len = height.length;
//System.out.println("maxArea: len:" + len);
int max = 0;
int temp = 0;
int i = 0, j = 0;
for (; i < len; i++) {
for (j = i + 1; j < len; j++) {
temp = (Math.min(height[i], height[j])) * (j - i);
if (max < temp) {
//System.out.println("maxArea: i:" + i + " j:" + j);
max = temp;
}
}
}
return max;
}
//直观的解释是:容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积
//所以我们从长度最长时开始递减,然后寻找更高的线来更新候补;
//还是从两头向中间靠拢的解法
public static int maxArea1(int[] height) {
int len = height.length;
int max = 0;
int i = 0, j = len - 1;
while (i < j) {
max = Math.max(Math.min(height[i], height[j]) * (j - i), max);
if (height[i] < height[j]) {
int m = i + 1;
while (m < j && height[m] < height[i]) {
m++;
}
i = m;
} else {
int m = j - 1;
while (m > i && height[m] < height[j]) {
m--;
}
j = m;
}
}
System.out.println("maxArea1: i:" + i + " j:" + j);
return max;
}
public static int maxArea2(int[] height) {
int i = 0, j = height.length - 1;
int max = 0;
while (i < j) {
max = Math.max(Math.min(height[i], height[j]) * (j - i), max);
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return max;
}
/**
* @param i
* @param j
* @returnmengdx-fnst
*/
public static void main(String[] args) {
//int[] test = { 1, 2, 3, 4, 8, 9, 6, 5, 4, 9, 6, 23, 48, 5, 6, 56, 5, 46, 6 };
int[] test = { 1, 2, 5, 4 };
System.out.println(maxArea(test));
System.out.println(maxArea1(test));
System.out.println(maxArea2(test));
}
}