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

leetcode005-Container With Most Water

2017-10-08 15:25 302 查看
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.
这是一道比较有意思的题目,最简单的做法是每条垂线两两组合,直接选出当中围成的最大面积。但这样子就比较乏味呢,细想一下,当中有哪些组合是可以在进行过程中不断被排除的呢?
S=height*width,height由两条垂线中最短的那条决定,width由两条垂线的距离决定。那么我们先选定在两端的两条,这时width最大,height是当中短的那条的长度。计算出这次的结果S‘后,就可以排除掉短的那条与任意其他垂线的组合,因为当我们选定短的这条后,再去选择其他的话得到的结果只可能小于本次结果,因为width肯定是减小了,而height最多是这条短的长度,所以S一定没有S’大。
以下是AC的代码
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int max = 0;
int l = 0, r = n-1;
while (l < r) {
int t = (r-l)*min(height[l],height[r]);
if (t > max) {
max = t;
}
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: