【leetcode】Container With Most Water(middle)

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

思路:

肯定是要确定水槽的左右边界位置,需要两个变量l1,l2 分别从最左边和最右边收缩。收缩规则是,比较矮的那一边向中间靠拢。更新水量。

我自己的代码:

int maxArea(vector<int> &height) {
int ans = (height.size() - ) * min(height[], height.back()) ;
int l1, l2, h1, h2;
h1 = ; h2 = height.size() - ;
l1 = h1; l2 = h2;
while(l1 < l2)
{
if(height[l1] > height[h1])
{
h1 = l1;
int tmp = (l2 - l1) * min(height[l2], height[l1]);
ans = (tmp > ans) ? tmp : ans;
}
if(height[l2] > height[h2])
{
h2 = l2;
int tmp = (l2 - l1) * min(height[l2], height[l1]);
ans = (tmp > ans) ? tmp : ans;
}
if(height[l1] < height[l2])
{
l1++;
}
else if(height[l1] > height[l2])
{
l2--;
}
else
{
l1++; l2--;
}
}
return ans;
}

大神的代码就简洁很多:

int maxArea(vector<int> &height) {
int left = , right = height.size() - ;
int maxWater = ;
while(left < right){
maxWater = max(maxWater, (right - left) * min(height[left], height[right]));
height[left] < height[right] ? left++ : right--;
}
return maxWater;
}
上一篇:spring源码深度解析— IOC 之 bean 创建


下一篇:easyUI和bootstrap的混搭