11. Container With Most Water

解决一个经典的编程面试题,即给定一系列高度不等的垂直线,如何找到两个线段,与x轴构成的容器能容纳最多的水。通过双指针技巧实现高效算法。

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

####问题描述
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

题目链接:

####思路分析
给一个高度的数组,使得形成的容器的容积最大。

容积 = min(height) * abs(i - j)。正常的暴力破解 O ( n ) O(n) O(n)会TLE,所以我们假定一开始相距最远的两根形成的container的容积是最大的,而指针移动的条件则是不断的去寻找更高的height,因为更高的height才能保证弥补i和j之间的差距,逐步向中间靠近。

####代码

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

时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)


####反思
很巧妙的方法,也不像动态规划,但是非常有效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值