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.
第一印象就是暴力求解法,用两个循环O(N^2)时间复杂度,我以为这道题很简单,结果还是我太年轻,当我看到一个连续15000个数的案例时,直接给跪,不用说超时了。
int maxArea(int* height, int heightSize)
{
int max=0,i,j,minheight,temp;
for(i=0;i<heightSize;i++)
for(j=i+1;j<heightSize;j++)
{
minheight=height[i]<height[j]?height[i]:height[j];
temp=minheight*(j-i);
max=temp>max?temp:max;
}
return max;
}
后来我去看别人写的,发现了一种贪心算法,时间复杂度为O(N)。它的思想类似贪心算法,用两个下标i,j分别指向两端,比较它们的高度假设height[i]小于height[j],矩形的面积(j-i)*height[i]如果大于之前的最大面积就更新,接下来一步就是移动i或者j。移动哪个呢,假设向左移动j,矩形的底边减少了,不论此时的height[j]是比之前增大还是减少,矩形的面积都是减少,所以应该向右移动i。所以原则就是那边高度低就移那边。很巧妙,但是我想不到啊,还是要勤加练习。这样运行时间8ms,击败70%的人。
int maxArea(int* height, int heightSize)
{
int max=0,i,j,minheight,temp;
for(i=0,j=heightSize-1;i<j;)
{
minheight=height[i]<height[j]?height[i]:height[j];
temp=(j-i)*minheight;
max=temp>max?temp:max;
if(height[i]<height[j])
i++;
else
j--;
}
return max;
}