题目描述
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器
一、算法描述
这个题首先想到的是使用双重循环,通过暴力方法,将数组中的所有大小的容器能盛的水计算出来,求出其中装水的最大体积,时间复杂度为 O ( N 2 ) O(N^2) O(N2)。另一种方法是使用双指针,初始化左右指针分别指向数组的左右端点,比较两个端点数值大小,将指向小端点的指针向中心移动(如果是左指针则向右移动,如果是右指针则向左移动)。这样只需要遍历一次数组就可以求出数组中能装水的最大值。伪代码如下所示:
int left=0,right=array.length-1;
int result=min(array[left],array[right])*(right-left)
int temp=0
while(left<right)
temp=0;
if(array[left]<=array[right]) left++
else right--
temp=min(array[left],array[right])*(right-left)
if(temp>result) result=temp
return result
二、JAVA 实现
public int maxArea(int[] height) {
int leftIndex=0,rightIndex=height.length-1;
int result=Math.min(height[leftIndex],height[rightIndex])*(rightIndex-leftIndex);
int temp;
while (leftIndex<rightIndex){
temp=0;
if (height[leftIndex]<=height[rightIndex]) leftIndex++;
else rightIndex--;
temp=Math.min(height[leftIndex],height[rightIndex])*(rightIndex-leftIndex);
if (temp>result) result=temp;
}
return result;
}
总结
涉及到左右端点的问题,可以考虑双指针的解法,能够在一定程度上减少时间复杂度。