题目:
Title:
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.
算法:
class SolutionContainerWithMostWater{
public static int maxArea(int[] height) {
// excellent method
int left = 0, right = height.length - 1;
int area, maxArea = (right-left)*(Math.min(height[left], height[right]) );
int left0 = left, right0 = right;
while(left<right){
if(height[left]<=height[right]){
while(height[++left]<=height[left0] && left < right);
left0 = left;
area = (right-left)*( Math.min(height[left], height[right]) );
if(area>maxArea){
maxArea = area;
}
}else{
while(height[--right]<=height[right0]);
right0 = right;
area = (right-left)*( Math.min(height[left], height[right]) );
if(area>maxArea){
maxArea = area;
}
} // else
} // while(left<right)
return maxArea;
} // int maxArea(int[] height)
}
算法亮点: o(n)复杂度,考虑一遍,求出最大值。最大值,肯定取到最两边,以此,轮流考虑两边最短值得情况下,取得的最大值!
我的算法:
class SolutionContainerWithMostWater{
public static int maxArea(int[] height) {
int maxArea = 0; // for return the last maxArea
int area[] = new int[height.length]; // for note each possibility
// note each possible match
for(int i = 0; i < area.length; i++){
a. ///
for(int j = i+1; j < area.length; j++){
// get shorter height from height[i] and height[j]
int shortOne = (height[i]>height[j]) ? height[j] : height[i];
// get max area[i]
area[i] = (area[i] > (shortOne*(j-i) ) ) ? area[i] : (shortOne*(j-i) );
}
b. /
for(int j = area.length-1; j > i; j--){
if(height[i]>height[j]){
area[i] = (area[i] > (height[j]*(j-i) ) ) ? area[i] : (height[j]*(j-i) );
}else{
area[i] = (area[i] > (height[i]*(j-i) ) ) ? area[i] : (height[i]*(j-i) );
break;
}
}
} // for(i)
// get the max area from area[] and put it in maxArea
for(int i = 0; i < area.length; i++){
maxArea = (maxArea > area[i]) ? maxArea : area[i];
}
return maxArea;
} // int maxArea(int[] height)
}
我的算法:
a. 一般考虑算法,顺序向后求出每个柱子的最大值,然后扫描一遍可得最大值,O(n*n)复杂度,但是便于理解!
b. 对a算法改进,对于前面的每个柱子,从后面考虑它的最大值,直到找到第一个比它高的柱子则没必要再找,但是对于递减序列,复杂度仍旧很高!