container-with-most-water

本文介绍了一种寻找能容纳最多水的容器的算法。通过从两端向中间遍历的方式,对比左右两侧高度来逐步缩小范围,最终确定最大盛水量。适用于至少包含两个元素的数组。

摘要生成于 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. 

给定 n 个正整数 a1a2,...,an,其中每个点的坐标用(iai)表示。 画 n 条直线,使得线 i 的两个端点处于(i,ai)和(i,0)处。请找出其中的两条直线,使得他们与 X 轴形成的容器能够装最多的水。

注意:你不能倾斜容器,n 至少是2。

解题思路:

    这道题其实和42雨水题差不多,这道题也是从两边向中间遍历,找到最大的那个容器即可.

实现代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值