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.
题目大意:一排数组保存了一排竹竿的高度,数组index的号码即竹竿编号和相对位置。要求的是两个竹竿所围成的最大面积=竹竿距离*最矮的那个竹竿高度。
题目解法有两种:
(1)两重for循环枚举所有可能的竹竿组合,计算可能的最大面积。然而这种方法必然超时,因为时间复杂度是O(n2)。即使代码中第二层循环的index是j从i+1处开始的,也会超时,也就是说LeetCode封死了想用两层循环解题的思路。然而还是给出反面的教材吧,见代码。
public class Solution {
public int maxArea(int[] height) {
int maxarea=0;
for(int i=0;i<height.length;i++){
for(int j=i+1;j<height.length;j++){
int area=(j-i)*(height[i]>height[j]?height[j]:height[i]);
if(area>maxarea)maxarea=area;
}
}
return maxarea;
}
}
(2)在O(n)的时间复杂度内解决问题
看到问题之后我一直在思考,这道题的最优解是否具有最优子问题的嵌套性质。想了半天没什么思路,还是跳出来放弃套路算法,好好分析一下。
注意到,在解法一中,我们每次都会从两个竹竿中选出一个最矮的作为计算高度对吧?那这不就是面积计算的短板了嘛。另一个较高的竹竿高度人家又没拖后腿,所以搜索的时候index的改变就不要动那个较高的竹竿了。由此思路,写出从数组两端向内开始搜索的代码,如下所示。
public class Solution {
public int maxArea(int[] height) {
int maxarea=0,area=0;
for(int i=0,j=height.length-1;i<j;){
if(height[i]>height[j]){
area=(j-i)*height[j];
j--;
}
else {
area=(j-i)*height[i];
i++;
}
if(area>maxarea)maxarea=area;
}
return maxarea;
}
}
这样改进之后,效果非常好,毕竟是O(n)的代码呀,sub一下试试,果然AC,偷笑~~~