Leetcode11 Container With Most Water
2016-07-21 17:26
519 查看
题目地址:
https://leetcode.com/problems/container-with-most-water/ 描述:
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.
分析
从两头向中间靠拢,找height更高的值。在收缩区间的时候优先从 x, y中较小的边开始收缩。同时从两边收缩是错的,比如[1,2,4,3],答案该是指向(2,3),而采用两边同时收缩会是(2,4)。
代码
class Solution {
public:
int maxArea(vector<int>& height) {
int l=0,r=height.size()-1;
int mx=0,now;
while(l<r){
now=min(height[l],height[r])*(r-l);
mx=max(mx,now);
if(height[l]<height[r]){
int t=l+1;
while(height[t]<=height[l] && t<r)
t++;
l=t;
}else{
int t=r-1;
while(height[t]<=height[r] && t>l)
t--;
r=t;
}
}
return mx;
}
};
https://leetcode.com/problems/container-with-most-water/ 描述:
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.
分析
从两头向中间靠拢,找height更高的值。在收缩区间的时候优先从 x, y中较小的边开始收缩。同时从两边收缩是错的,比如[1,2,4,3],答案该是指向(2,3),而采用两边同时收缩会是(2,4)。
代码
class Solution {
public:
int maxArea(vector<int>& height) {
int l=0,r=height.size()-1;
int mx=0,now;
while(l<r){
now=min(height[l],height[r])*(r-l);
mx=max(mx,now);
if(height[l]<height[r]){
int t=l+1;
while(height[t]<=height[l] && t<r)
t++;
l=t;
}else{
int t=r-1;
while(height[t]<=height[r] && t>l)
t--;
r=t;
}
}
return mx;
}
};
相关文章推荐
- [转] Linux 中/var/spool/postfix/maildrop目录下堆积大量小文件
- 2016 Multi-University Training Contest 2 1001 hdu 5734 暴力
- 2016 Multi-University Training Contest 2 1005 hdu 5738 计算几何
- 线程与信号
- BIO | NIO | AIO释疑
- AIO与BIO接口性能对比
- 2016 Multi-University Training Contest 1
- mac 命令行 Please try running this command again as root/Administrator
- (POJ1273)Drainage Ditches(裸最大流,EK模板)
- 2016 Multi-University Training Contest 2 Acperience
- Lock wait timeout exceeded; try restarting transaction
- E - Raising Modulo Numbers
- HDU5724 2016 Multi-University Training Contest 1 (SG+预处理)
- 接口和抽象的解释!(转载自http://blog.csdn.net/fenglibing/article/details/2745123)
- 批量创建客户主数据函数SD_CUSTOMER_MAINTAIN_ALL
- aidl的使用方法
- http://blog.csdn.net/lmj623565791/article/details/37620057
- 无法解析的外部符号 _main解决办法
- POJ 1995 Raising Modulo Numbers(快速幂)
- POJ 1995 Raising Modulo Numbers