leetcode 11.盛最多水的容器

11. 盛最多水的容器

双指针法,挺常用的,学习一下。

class MaxArea {
public:
    int maxArea(vector<int>& height) {
        if (height.size() < 2)
        {
            return 0;
        }
        int nLeft = 0;
        int nRight = height.size() - 1;
        int nMaxArea = 0;
        while (nLeft < nRight)
        {
            int nLeftVal = height[nLeft];
            int nRightVal = height[nRight];
            int nVal = nLeftVal < nRightVal ? nLeftVal:nRightVal;
            if (nMaxArea < nVal * (nRight - nLeft))
            {
                nMaxArea = nVal * (nRight - nLeft);
            }
            if (nLeftVal < nRightVal)
            {
                nLeft++;
            }
            else
            {
                nRight--;
            }
        }
        return nMaxArea;
    }
};

猜你喜欢

转载自blog.csdn.net/yxccc_914/article/details/79689171