[Leetcode] 11. Container With Most Water 解题报告

本文介绍了一种寻找能盛最多水的容器的高效算法。针对给定的一系列坐标点,利用双指针技巧,在O(n)的时间复杂度内找出两个线段与x轴构成的最大面积。文章对比了暴力枚举法与双指针法,详细解析了双指针法的实现逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

思路

1、暴力枚举法:显而易见的思路是两重循环,暴力枚举所有可能的containter,时间复杂度为$O(n^2)$。然而显而易见该方法无法通过Leetcode的测试以及面试官。

2、双指针法:首先设置左右两个指针,并初始化当前容器的容量。接着比较左右指针的高低,如果左边更低,则左指针持续右移直到遇到比当前左指针更高的指针;否则右指针左移直到遇到比当前右指针更高的指针,随后更新容量。其原理是:因为我们是从宽度最大的容器开始搜索的,那么要获得更大的容量,唯一的可能就是更新后的min(left, right)大于当前的min(left, right)。上述指针移动的规则正是基于该原理设计的。该方法的时间复杂度为O(n),空间复杂度为O(1)。


代码

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0, right = height.size() - 1, index = 0;
        int max_area = min(height[left], height[right]) * (right - left);
        while(left < right)
        {
            if(height[left] > height[right])    // decrease right
            {
                index = right - 1;
                while(index > left && height[index] <= height[right])
                    --index;
                right = index;
            }
            else                                // increase left
            {
                index = left + 1;
                while(index < right && height[index] <= height[left])
                    ++index;
                left = index;
            }
            max_area = max(max_area, min(height[left], height[right]) * (right - left));
        }
        return max_area;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值