LeetCode - 11. Container With Most Water - C++

两个指针法。此题精髓在于判断如何移动指针:移动小的那个。因为高度取决于小的那个,所以移动小的才有可能增加。

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

猜你喜欢

转载自blog.csdn.net/L_bic/article/details/89202924
今日推荐