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

11. Container With Most Water

2015-06-05 09:21 288 查看
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)的算法:

矩阵的行代表第一根线,矩阵的列代表第二根线,假设我们有6根线。

在下图中,x表示不用计算体积的情况:(1)对角线,表示两条线重合(2)对角线的下三角和上三角是对称的。

一开始,我们计算(1,6)处的体积,用o表示。现在假设左侧的线比右侧的线短,那么第一行中(1,6)左侧所有点处的体积都要更小,即无论如何移动第二条线体积都会减小(a,其他点更高时,体积仍根据左侧线的高度算;b,其他点更低时。两种情况下,宽度变小),所以这些点我们都不需要计算。

所以我们将左侧的线移到2,计算(2,6)处的体积。现在假设右边的线更短,那么同一列(2,6)点之下的点体积都更小,即无论如何移动第一条线,体积都会更小(a,其他点更高时,体积仍根据左侧线的高度算;b,其他点更低时。两种情况下,宽度变小),所以这些点我们不需要计算。

无论o的路径是怎样的,我们只需要找到路径上的最大值即可。

class Solution {
public:
int maxArea(vector<int> &height) {
int l = 0;
int r = height.size()-1;
int maxArea = 0;
int curArea;
while(l < r)
{
curArea = min(height[l],height[r]) *(r - l);

if(curArea > maxArea)
maxArea = curArea;
if(height[l] < height[r])
l++;
else
r--;
}

return maxArea;
}
};

1.宽度最大的容器是一个比较好的初始选择,即使用第一条线和最后一条线。

2.其他所有的容器的宽度都比1中容器的宽度要小,所以只有通过增加线的高度来获得容积更大的容器。

3.根据2的分析可以知道,在左右两条线中,去掉高度较小的那一个,只一种比较保险的方法。

class Solution {
public:
    int maxArea(vector<int> &height) {
        int l = 0;
        int r = height.size()-1;
        int maxArea = 0;
        int curArea;
        while(l < r)
        {
            curArea = min(height[l],height[r]) *(r - l);
            
            if(curArea > maxArea)
                maxArea = curArea;
            if(height[l] < height[r])
                l++;
            else
                r--;
        }
        
        return maxArea;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: