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;
}
};
..., 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;
}
};
相关文章推荐
- 11. Container With Most Water
- 第65题 Container With Most Water
- [LeetCode]Container With Most Water
- Container With Most Water
- LeetCode OJ - Container With Most Water
- 11. Container With Most Water
- LeetCode Solutions : Container With Most Water
- CODE 120: Container With Most Water
- #LeetCode OJ #11 Container With Most Water
- LeetCode 11---Container With Most Water
- Array(9) -- Container With Most Water,Insert Delete GetRandom O(1) I, II
- [Leetcode P11]Container With Most Water
- 11. Container With Most Water
- Container With Most Water
- leetcode Container With Most Water
- Leetcode11 Container With Most Water
- LeetCode Container With Most Water
- LeetCode By Scala Container With Most Water
- 11. Container With Most Water
- Container with most water