力扣hot100——11. 盛最多水的容器

题目链接: 11. 盛最多水的容器 - 力扣(LeetCode)
思路: 贪心加双指针。首先先让宽度最大,左指针指向最左端,右指针指向最右端;然后左右指针收缩,此时必然导致宽度减小,如果高度也减小必然不是最大值,而高度由左右指针最小的一个决定,因此移动其中最小的一个。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left=0,right=height.size()-1;//初始化左右指针
        int ans=0;
        while(left<right){
            ans=max(ans,(right-left)*min(height[left],height[right]));
            //移动指针
            if(height[left]<height[right]) left++;
            else right--;
        }
        return ans;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
posted @ 2025-04-16 17:00  林下清风~  阅读(36)  评论(0)    收藏  举报