LeetCode 之 Container With Most Water — C 实现

本文探讨了如何解决容器盛水问题,通过两种算法对比,介绍了时间复杂度为O(n²)的遍历方法和时间复杂度为O(n)的两端逼近法。后者通过从两端向中间查找并记录最大值来提高效率。

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

Container With Most Water

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.

给定 n 个非负整数 a1a2, ..., an,以元素下标为横坐标组成坐标点 (iai),过这些点做垂直于x轴的垂线,找出两根线和横坐标一起组成一个容器,使容器能存储最多的水。

注意:不能倾斜容器。

分析:

法1:从左向右逐个计算两根线组成的容器,总是记录最大的值。复杂度为 O(n²),出现 Time Limited.

法2:从两端向中间查找计算并记录最大值,如果存在更大的值,只有可能是存在高度比当前最小高度大的值;时间复杂度为 O(n).

int maxArea(int* height, int heightSize) {
    int lside = 0, rside = heightSize-1;
    int smallHeight = 0;
    int area = 0, mArea = 0;
    
    if(!height)//空
    {
        return 0;
    }
    
    while(lside < rside)
    {
        smallHeight = (height[lside] < height[rside])?height[lside]:height[rside]; //取较低的高度,决定水位
        area = (rside - lside)*smallHeight;
        if(area > mArea)
        {
            mArea = area;
        }
        //从两端向中间比较,比两端大的只可能是最小边更大的边组成的面积
        if(height[lside] < height[rside])
        {
            ++lside;
        }
        else
        {
            --rside;
        }
    }
    
    return mArea;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值