您的位置:首页 > 大数据 > 人工智能

11. Container With Most Water

2016-10-31 16:09 337 查看
4000

题目:Container With Most Water

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.

就是说,x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an。找出两条线段,使他们和x抽围成的面积最大。面积公式是 Min(ai, aj) X |j - i|

1. 穷举法: 时间复杂度O(n*n),time limited exceed,超时不通过。

代码:

int maxArea(int* height, int heightSize) {
int i=0,j=0;
int max=0;

for(i=0;i<heightSize;i++)
for(j=i+1;j<heightSize;j++)
{
int tmp=(j-i)*(height[j]>height[i]?height[i]:height[j]);
if(tmp > max)
{
max=tmp;
}
}

return max;
}

2.线性复杂度:

有两个指针i和j分别指向头和尾, 如果a[i]<a[j], 则i++,否则j--:


证明:

对任意k<j:

都有(k-i)*min(a[k],a[i]) < (j-i)min(a[j],a[i]) = (j-i)a[i]

因为:

(k-i) < (j-i)

min(a[k],a[i]) < a[i] < min(a[j],a[i])

所以此种情况移动j只能得到更小的值, 移动j无用, 只能移动i。 反之亦然。

没懂!!!!!!

代码:

int maxArea(int* height, int heightSize) {
int i=0,j=heightSize-1;
int max=0;

while(i<j)
{
int tmp=(j-i)*(height[j]>height[i]?height[i]:height[j]);
if(height[i]<height[j])
{
i++;
}
else
{
j--;
}

if(tmp > max)
{
max=tmp;
}
}
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode