题目难度: Medium
原题描述:
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.
题目大意:
在平面直角坐标系的x轴上对(1,0)到(n,0)这n个点作n条长度不同的垂直于x轴的线段,问取其中哪两条线段与x轴形成的容器能装最多的水?
解题思路:
很容易能想到当选定两条线段时,能装的最多水量为(j-i)*min{ai, aj}。一开始看错题了,以为x轴坐标的点是不等距的,但这不影响整体的思路。由于要求的结果是由两部分相乘得到的,因此要令结果最大,则两部分都应该尽量取最大,但是这两部分并不是独立的,而是相关联的,因此并不能做到两部分同时取最大。最直接的做法是遍历两两线段,得出结果的最大值,但是这种做法的时间复杂度是O(n^2),显然不够好,直观上看应该有更好的算法。
一开始我想到的是,对于一条给定的线段,如果其它线段都比这条线段长,则选择离这条线段最远的线段就能得到最大的面积,但是如果其他线段有的比这条线段短,结果又不确定了,这正是我苦恼的地方。后来参考别人的做法才知道,这道题的突破口在于,选择最左和最右的两条线段,对于较短的线段,和它形成最大面积的线段就是这两条的另一条线段。把这个想通了,这道题就迎刃而解了。
时间复杂度分析:
由于解法是设置两个指针分别指向最左和最右,然后再向中间移动直至遇上,因此只需扫描一遍数组,时间复杂度是O(n)。
以下是代码:
int maxArea(int* height, int heightSize)
{
int ans = 0;
int i,j,minHeight,area;
for(i=0,j=heightSize-1 ; i<j ; ){
minHeight = (height[i]<height[j] ? height[i] : height[j]);
area = minHeight * (j-i);
ans = (ans>area ? ans : area);
while(height[i]<=minHeight && i<j)
++i;
while(height[j]<=minHeight && i<j)
--j;
}
return ans;
}