LeetCode有最多水的容器

这篇博客讨论了LeetCode上的Container With Most Water问题,该问题要求找到能容纳最多水的两个垂直线。传统的O(n^2)解决方案超出了时间限制,因此提出了使用双指针法的O(n)解决方案。在每次迭代中,通过比较两个指针所指高度的较小值来计算当前容积,并与最大容积比较更新。如果左侧高度较小,则移动左指针,反之移动右指针,直到两指针相遇。这种方法有效地找到了最大的水量。示例代码展示了如何实现这一算法。

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

LeetCode: Container With Most Water

问题描述

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i,height).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example1
在这里插入图片描述

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example2

Input: height = [1,1]
Output: 1

方法思路
首先想到的方法是嵌套循环遍历数组,复杂度为O(n2), 但是程序运行结果超出了限制,因此复杂度应该控制在O(n), 即遍历一次数组。因为有两个因素会影响容器的容积,即宽度(两点之间的距离),最小高度(两个点对应的值中较小的一个), 初始宽度设置最大((height.length - 1) - 0)并逐渐缩小宽度,再乘以最小高度并将结果与当前最大容积进行比较以决定是否更新最大容积,在完成比较后,比较两个点对应的值,在宽度缩小的情况下,要使容积变大,就只能抛弃更小的高度值以此来进行循环。

代码如下(示例):

class Solution {
    public int maxArea(int[] height) {
        int l = 0;
        int r = height.length-1;
        int maxArea = 0;
        
        while(l<r){
            maxArea = Math.max( maxArea, Math.min(height[l],height[r])*(r-l) );
            
            if(height[l] < height[r]){
                l++;
            }else{
                r--;
            }
        }
        
        return maxArea;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值