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.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
tag: array, two pointers
method 1 brute force
暴力解,两层遍历循环. 简单地考虑每个可能的线对的面积,并找出其中的最大面积。
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++)
maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i));
return maxarea;
}
}
method 2 two pointers
找到最高的线,然后找到左边的最高的线和右边的最高的线,他们之间的面积就是最大的面积。如果有多个相同的最高线,可能要尝试多次
method 3
两根指针法,left和right,每次移动短的那一段,因为如果移动大的,那么在另一端不变的情况下,水量可能会变小,首先宽变小一位,而高度始终是以小的算的。相对来说移动小的,在宽度变小的情况下,更容易获得更大的面积
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(maxArea, Math.min(height[left], height[right])
* (right - left));
if (height[left] < height[right])
left++;
else
right--;
}
return maxArea;
}
summary:
- 思考逻辑链:算面积->需要知道长宽-> 宽的话取决于两边短的一边-> 两边-> 两个指针法
- 以什么样得标准遍历能得到更大的面积,移动短那一段