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.
在二维坐标系中,(i, ai) 表示 从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积
分析:这道题最明显的解法就是暴力解法,不过时间复杂度为O(n^2),这里我们采用的是Two Pointer的方法,时间复杂度为O(n)
思路:用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移(此时右端左移得到的结果只会变小),反之右端左移(同理),直到左右两端移到中间重合, 记录这个过程中每一次组成木桶的容积,返回其中最大的。
public class Solution {
public int maxArea(int[] height) {
int start = 0;
int end = height.length-1;
int maxArea = 0;
while (start < end)
{
if (min(height[start],height[end])*(end-start)>maxArea)
maxArea = min(height[start],height[end])*(end-start);
if (height[start] < height[end])
{
start++;
}
else
{
end--;
}
}
return maxArea;
}
public int min(int a, int b)
{
return (a>b?b:a);
}
}