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

第一周算法设计与分析:Container with most water

2017-02-25 16:40 211 查看
题目来自此处




描述如下:

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.

O(n^2)算法:

一开始是想从前往后扫描,一条边不断与右边剩余的所有边匹配。但是这种算法在数据较多的情况下超时。

所以还是放弃这种懒惰做法


O(n)算法:

这个其实是一个求面积最大化的问题。考虑一个初始值——使x轴上的边最大化作为宽度,高度是min(a1,an)。

然后,作为高度的两条边,不断往中心推进,直到左端大于右端,则停止迭代。其中比较关键的地方在于,在迭代过程中左端高度与右端高度的比较,如果左端的高度小于右端的高度,表明左端的高度是作为整体面积的高度,那么他跟右端之间所有边组成的容器都以他为高度(然而可能还有更矮的),这些可能的组合不可能比目前组合的面积大。所以舍弃左端与这些边的组合,即左端往右移。反之如果左端的高度大于右端的,那么右端往左移。

关键的代码如下:

int maxArea(vector<int> height)
{
int cur_i = 0;
int cur_j = height.size()-1;
int water_max = (height.size()-1)*min(height[i],height[j]);
while(cur_i<cur_j)
{
water_max = max(water_max,min(height[cur_i],height[cur_j])*(cur_j-cur_i));
if(height[cur_i]<height[cur_j])
cur_i++;
else
cur_j--;

}
cout<<water_max<<endl;
return water_max;
}
height包含所有边。

大概就这样咯~想个算法真的可以想到头皮发麻~

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