题目:
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.
本题是为了寻找最大容积的两条直线。需要衡量的点主要是高度和宽度之间的权衡。首先我们想到的最简单的思路应该是使用暴力搜索法,使用两次遍历的方法分别对每个数搜索其最大容积。代码入下:
public int maxArea(int[] height) {
int max = 0;
for(int i=0; i<height.length-1; i++){
int tmp = height[i];
for(int j=i+1; j<height.length; j++){
max = Math.max(max, (j-i)*Math.min(tmp, height[j]));
}
}
return max;
}
但是这种方法会产生TLE,时间超出限制。所以我们相到下面的方法,分别从左右两边开始搜索,用max记录最大值,然后不断遍历。每次遍历的依据是看左右两边的值那个大,将小的移向下一位置。代码入下:
public int maxArea1(int[] height){
int max = 0, left=0, right=height.length-1;
while(left < right){
if(height[left] < height[right]){
max = Math.max(max, (right-left)*height[left]);
left ++;
}else{
max = Math.max(max, (right-left)*height[right]);
right --;
}
}
return max;
}
上面这种方法客击败88。5%的用户,但是我们很显然还可以进行改进,就是每次都移动多次,这样可以省去计算最大值的时间,击败99。2%的用户。代码入下:
public int maxArea2(int[] height) {
int lo = 0;
int hi = height.length - 1;
int max = 0;
while(lo < hi) {
int min = Math.min(height[lo], height[hi]);
max = Math.max(max, min * (hi - lo));
while(lo <= hi && height[lo] <= min) lo++;
while(lo <= hi && height[hi] <= min) hi--;
}
return max;
}