leetcode 11. 盛最多水的容器

leetcode 11. 盛最多水的容器
解题思路:双指针
每次向内移动矮的指针,因为如果向内移动高的指针,面积一定会变小;如果向内移动矮的指针,面积还有可能变大。

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

        }
        return maxWater;
    }
};

你可能感兴趣的:(leetcode,双指针,leetcode,算法)