本文介绍: 考虑到盛水容器的特殊性。双指针从开始遍历,遍历过程中。不知道原理。

题目:

考虑到盛水容器的特殊性。双指针从最两边开始遍历,遍历过程中舍弃最小的

不知道原理。

模板的:

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param height int整型vector 
     * @return int整型
     */
    int maxArea(vector<int>& height) {
        // write code here
        int n = height.size();
        if(n < 2)
            return 0;
        
        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])
                l++;
            else
                r--;
        }
        return ans;
    }
};

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注