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

[LeetCode] Container With Most Water

时间:2015-04-18 17:44:43      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Container With Most Water

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.

解题思路:

这道题的意思是直角平面上有n条垂直于x轴的线,相邻的线相距1,选取两根线,与x轴构成一容器。求这样的容器能最多够装多少水?

1、基本方法,两两组合,计算出最大值。时间复杂度为O(n^2)。产生超时错误。

class Solution {
public:
    int maxArea(vector<int>& height) {
        //naiv办法
        int len = height.size();
        if(len<2){  //至少要有两个以上的线方能组成容器
            return 0;
        }
        int maxArea=0;
        int minHeight = 0;
        for(int i=1; i<len; i++){
            minHeight = height[i];
            for(int j=i-1; j>=0; j--){
                minHeight = min(height[i], minHeight);
                if(minHeight==0){
                    break;
                }
                maxArea=max(maxArea, minHeight*(i-j));
            }
        }
        return maxArea;
    }
    
    int min(int a, int b){
        return a>b?b:a;
    }
    
    int max(int a, int b){
        return a>b?a:b;
    }
};
2、比较talent的办法,两边夹,若左边木板小于右边,移动左边木板,否则移动右边木板。因为只有这样容量才有可能变大。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxArea = 0;
        int len = height.size();
        int i=0, j=len-1;
        while(i<j){
            maxArea=max(maxArea, min(height[i], height[j])*(j-i));
            if(height[i]<height[j]){
                i++;
            }else{
                j--;
            }
        }
        
        return maxArea;
    }
    
    int max(int a, int b){
        return a>b?a:b;
    }
    
    int min(int a, int b){
        return a>b?b:a;
    }
};


[LeetCode] Container With Most Water

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45114885

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