【题解】11.盛最多水的容器(贪心、数组、双指针)

https://leetcode.cn/problems/container-with-most-water/description/?envType=study-plan-v2&envId=top-100-liked
在这里插入图片描述

双指针法:
关键字:左右两边
模式识别:需要移动左右两头的问题可以考虑双指针
难点:如何移动指针

  • 相同情况下两边距离越远越好
  • 区域受限于较短边

利用单调性!

class Solution {
    
    
public:
    int maxArea(vector<int>& height) {
    
    
        int left = 0, right = height.size() - 1; // 右指针记得-1 
        int ret = 0;
        while (left < right)
        {
    
    
            int v = min(height[left], height[right]) * (right - left);
            ret = max(ret, v);
            if (height[left] < height[right]) 
            {
    
    
                left++;
            }
            else
            {
    
    
                right--;
            }
        }
        return ret;
    }
};

猜你喜欢

转载自blog.csdn.net/Colorful___/article/details/141213363