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

[leetcode] 11. Container With Most Water

2016-03-07 15:16 330 查看
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.

这道题是找最大容器,题目难度为Medium。

双层循环暴力比对的方法估计会超时,就不尝试了。

我们拿a1和an组成的容器作为初始容器,容器容积为min(a1,an)*(n-1),把(n-1)记为长,min(a1,an)记为高。计算容器容积时要考虑到长的因素,以min(a1,an)为高的其他任何容器都不会比初始值大,因为其他容器高最大为min(a1,an),而长必定小于(n-1),所以a1和an中小的那条线在后续比较中就可以不考虑了。如果min(a1,an)==a1,我们继续查看a2和an组成的容器,否则查看a1和an-1组成的容器,同时更新最大容器值。依照这样的策略逐步缩小范围,最终就得到了最大容器。具体代码:class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int maxWater = 0;
while(l < r) {
maxWater = max(maxWater, min(height[r],height[l])*(r-l));
if(height[l] < height[r]) ++l;
else --r;
}
return maxWater;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Two Pointers