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

[LeetCode] Container With Most Water

时间:2014-07-30 12:05:03      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   

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.

最直观的方法,把每两两之间的容器面积算出来,找出最大的,时间复杂度O(n^2),不出所料Time Limit Exceeded!这种笨方法如下所示:

class Solution {
public:
    int maxArea(vector<int> &height) {
        int num = height.size();
        int MaxArea = 0;
        if(num<=1)
            return MaxArea;

        for(int i=0;i<num-1;i++){
            for(int j=i+1;j<num;j++)
              MaxArea = max(MaxArea,(j-i)*min(height[i],height[j]));
        }//end for
        return MaxArea;
    }
};

所以要探索简单的方法,遍历所有两两之间的面积中,有很多是无用功,比如S =height[0,len-1];如果height[0]<height[len-1],

那么maxS = max(S,height(1,len-1)),这样就省略了[0,1]、[0,2]....[0,len-2]计算S,

因为此时max([0,1]、[0,2]....[0,len-1]) = height[0,len-1],具体编程如下:

    int maxArea(vector<int> &height){
         int num = height.size();
         int MaxArea = 0;
         if(num<=1)
            return MaxArea;
         int low = 0, high = num-1;
         while(high>low)
         {
         
           MaxArea = max(MaxArea,(high-low)*min(height[high],height[low]));
           if(height[high]>height[low])
               low++;
           else
               high--;
         
         }
        return MaxArea;
    } 

 

[LeetCode] Container With Most Water,布布扣,bubuko.com

[LeetCode] Container With Most Water

标签:style   blog   color   os   io   for   ar   div   

原文地址:http://www.cnblogs.com/Xylophone/p/3877575.html

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