码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Container With Most Water(middle)

时间:2015-02-05 21:41:14      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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() - 1) * min(height[0], height.back()) ;
        int l1, l2, h1, h2;
        h1 = 0; h2 = height.size() - 1;
        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 = 0, right = height.size() - 1;
    int maxWater = 0;
    while(left < right){
        maxWater = max(maxWater, (right - left) * min(height[left], height[right]));
        height[left] < height[right] ? left++ : right--;
    }
    return maxWater;
}

 

【leetcode】Container With Most Water(middle)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4275912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!