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

leetcode 11. Container With Most Water

2016-04-27 09:41 369 查看
题目:

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.
描述:
提供了n个非负的整数a1, a2,
..., an,每个代表了一个在坐标系中的点(i, ai).这n个点与相对的点(i,
0)构成了垂直于x轴的直线。找出其中两根直线,使得它们之间围成的谁容量最大。

每条垂直于x轴的线,两个端点是(i,ai)(i,0),每两条直线之间相距为n个1的距离,那么两条直线之间的容量为高度较小的直线长度*(l2-l1),一个矩形大小。

令l1指向height[0],l2指向height[1],假设l2>l1,那么移动向左移动l2,就算l2变大,但是l1小,还是无法改变最大容量。l1 l2是否向中间移动,取决于移动后的容量。

也就是说,每次移动头部变量i和尾部变量j中的一个,哪个变量的高度小,就把这个变量向中心移动。计算此时的装水量并且和最大装水量的当前值做比较。

int maxArea(int* height, int heightSize) {

int i,j;
int l1,l2,tem;//l1,l2分别为选取的左右两根直线,它俩之间可以包含多条直线
int mwater=0;//水容量,初始化为0
int twater=0;

//令l1指向height[0],l2指向height[1],假设l2>l1,那么移动向左移动l2,就算l2变大,但是l1小,还是无法改变最大容量
//l1 l2是否向中间移动,取决于移动后的容量。
//也就是说,每次移动头部变量i和尾部变量j中的一个,哪个变量的高度小,就把这个变量向中心移动。
i=0;
j=heightSize-1;

while(i<j)
{
l1=height[i];
l2=height[j];
tem=l1>l2?l2:l1;
//水容量
twater=tem*(j-i);
if(twater>mwater)
{
mwater=twater;
}
if(l1<l2)
i++;
else
j--;

}

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