【力扣 - 盛最多水的容器】

本文介绍了解决给定整数数组表示的线段问题,通过双指针方法找到两条线段,使它们与x轴构成的容器能容纳最多水。算法的时间复杂度为O(n),空间复杂度为O(1)。

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

题目描述

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0)(i, height[i])

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。

示例1

在这里插入图片描述

示例2

输入:height = [1,1]
输出:1

提示:

n == height.length
2 <= n <= 10^5
0 <= height[i] <= 10^4

题解

双指针

1:使用两个指针,indexLeft和indexRight
2:面积的计算公式Area = high * wide,面积等于高 * 宽
3:计算high = fmin(height[indexRight] , height[indexLeft])
4: 计算wide = indexRight - indexLeft
5:计算出对应的Area与maxArea进行比较并更新maxArea
6: 移动indexRight 与 indexLeft中小的指针
时间复杂度:O(n)
空间复杂度:O(1)

代码

int maxArea(int* height, int heightSize)
{
    // Initialize two pointers, one at the start and one at the end of the array
    int indexLeft = 0;
    int indexRight = heightSize - 1;
    
    // Initialize the variable to store the maximum area
    int maxArea = 0;
    
    // Loop until the two pointers meet
    while (indexLeft < indexRight)
    {
        // Calculate the height of the container at the current positions
        int minHeight = fmin(height[indexLeft], height[indexRight]);
        
        // Calculate the width of the container
        int width = indexRight - indexLeft;
        
        // Calculate the area of the container
        int area = width * minHeight;
        
        // Update the maximum area if the current area is greater
        if (maxArea < area)
        {
            maxArea = area;
        }
        
        // Move the pointer with the smaller height towards the center
        if (height[indexLeft] < height[indexRight])
        {
            indexLeft++;
        }
        else
        {
            indexRight--;
        }
    }
    
    // Return the maximum area found
    return maxArea;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值