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

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: