LeetCode Day9 container_with_most_water

法一:穷举

class Solution {
public:
    int maxArea(vector<int>& height) {
        int v,max=0,h,l;
        for(int i=0;i<height.size()-1;i++){
            for(int j=i+1;j<height.size();j++){
                h=(height[i]<height[j])?height[i]:height[j];
                l=j-i;
                v=l*h;//printf("%d,%d,%d\n",h,l,v);
                if(v>max) max=v;
            }
        }
        return max;
        
    }
};

法二:双指针

class Solution {
public:
    int maxArea(vector<int>& height) {  //双指针
        int res = 0, i = 0, j = height.size() - 1;
        while (i < j) {
            res = max(res, min(height[i], height[j]) * (j - i));
            height[i] < height[j] ? ++i : --j;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/82971652