LeetCode.M11.盛最多水的容器

这篇博客主要介绍了如何使用双指针算法解决LeetCode中的第11题——盛最多水的容器。通过分析题目,确定了移动短板指针可以增加可能的水量面积,并给出了一段Java代码实现。在代码中,定义了两个指针l和r,分别从两端开始,每次移动短板指针,直到两指针相遇,过程中更新最大水量。时间复杂度为O(n),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

LeetCode.M11

题目:

在这里插入图片描述

题目大意:

​ 如图所示。

数据范围:

如图所示

思路:

​ 采用双指针,所容纳的水为min(h[l], h[r]) * (r - l) ,初始时l = 0,r = len - 1,接下来选择该移动哪边的指针。无论l或r向中间收缩一格,都会导致水槽底边宽度(r - l)变短:

  • 若向内移动短板 ,水槽的短板 min(h[i],h[j]) 可能变大,因此下个水槽的面积可能增大 。
  • 若向内移动长板 ,水槽的短板 min(h[i],h[j]) 不变或变小,因此下个水槽的面积一定变小 。

因此我们每次只需要向内移动短板的指针即可。

代码:

class Solution {
    public int maxArea(int[] height) {
        int l = 0, r = height.length - 1, res = 0;
        while (l < r){
            int hl = height[l], hr = height[r], t = r - l;
            if (hl < hr){
                res = Math.max(res, t * hl);
                l ++ ;
            }else {
                res = Math.max(res, t * hr);
                r -- ;
            }
        }
        return res;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{1,8,6,2,5,4,8,3,7};
        System.out.println(solution.maxArea(nums));
    }
}

时空复杂度分析等:

  • 时间复杂度 : O(n)

  • 空间复杂度 : O(1)

题目链接:

11. 盛最多水的容器 - 力扣(LeetCode)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值