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 and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

 

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

暴力直接过了击败了百分之12的人

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

整了个双指针,速度时间一下提升了不少

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

看到一段特别有意义的评论

证明很严谨。 其实无论是移动短指针和长指针都是一种可行求解。 只是,一开始就已经把指针定义在两端,如果短指针不动,而把长指针向着另一端移动,两者的距离已经变小了,无论会不会遇到更高的指针,结果都只是以短的指针来进行计算。 故移动长指针是无意义的。

最快的人咋写的?

class Solution {
public:
    int maxArea(vector<int>& height)
    {
        int maxarea = 0, l = 0, r = height.size() - 1;
        while (l < r) {
            int a = height[l] > height[r] ? height[r] : height[l];
            maxarea = maxarea > a * (r - l) ? maxarea : a * (r - l);
            if (height[l] < height[r])
                l++;
            else
                r--;
        }
        return maxarea;      
        
    }
};