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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
思路:暴力破解,用两个指针来计算每一格的面积,遍历数组,找到面积最大的即可
package com.wanghao;
public class ContainerWithMostWater {
public static void main(String[] args) {
// TODO Auto-generated method stub
ContainerWithMostWater containerWithMostWater=new ContainerWithMostWater();
int height[]= {1,8,6,2,5,4,8,3,7};
System.out.println(containerWithMostWater.maxArea(height));
}
public int maxArea(int[] height) {
int max=0;
for (int i = 0; i < height.length; i++) {
for (int j = 0; j < height.length; j++) {
if (height[i]<=height[j]) {
max=max>height[i]*(j-i) ? max:height[i]*(j-i);
}
if (height[i]>height[j]) {
max=max>height[j]*(j-i) ? max:height[j]*(j-i);
}
}
}
return max;
}
}
看了solution之后发现这样做实在太蠢了,用两个指针,有更简单的方法,两个指针分别在数组的两端,先计算出面积,然后移动指针(移动指向的内容较小的指针),继续计算面积,寻找最大的面积,知道两个指针碰到一起时结束,这样时间复杂度就下来了,只遍历了一遍数组。
为什么不移动指向的内容较大的指针呢,因为我们要找到的是最大的面积,移动指向的内容较大的指针不会使面积增加,只有移动指向的内容较小的指针才有可能使面积增加(即使两个指针之间的距离变小了)代码如下