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

Container With Most Water

时间:2015-06-15 09:36:47      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:

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.思路:x轴长度变小,则选择线段长度增大的值;从俩边向中间依次计算,选取最大值;

</pre><pre name="code" class="cpp">class Solution {
public:
    int max(int a,int b)
    {
        if(a > b)
          return a;
         else
         return b;
    }
    int min(int a,int b)
    {
        if(a < b)
          return a;
        else
         return b;

    }
    int maxArea(vector<int>& height) {
        int n = height.size();
        int i;
        int l = 0;
        int r = n-1;
        int ans = 0;
        while( l < r)
        {
            ans = max(ans,min(height[l],height[r])*(r-l));
            if(height[l] < height[r])
            {
                int k = l;
                while(k < r && height[k] <= height[l])
                  k++;
                l = k;
            }
            else
            {
                int k = r;
                while(k > l && height[k] <= height[r])
                 k--;
                r = k;
            }
        }
        return ans;
    }
};




Container With Most Water

标签:

原文地址:http://blog.csdn.net/sunshinemay_1014/article/details/46492615

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