【LeetCode】解题11:Container With Most Water

本文详细解析了LeetCode第11题“Container With Most Water”的两种解题策略:暴力求解与双指针法。通过对比,突出了双指针法在效率上的优势,其时间复杂度仅为O(n),并提供了Java实现代码。

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

Problem 11: Container With Most Water [Medium]

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 and n is at least 2.
在这里插入图片描述
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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

来源:LeetCode

解题思路

1. 暴力求解

使用二重循环,遍历 n ( n − 1 ) 2 \frac{n(n-1)}{2} 2n(n1)对组合的容量,返回最大值。
时间复杂度O( n 2 n^2 n2)。

2. 双指针

使用双指针指向数组的头和尾,并在循环中不断将指向较短线段的指针向内移动,同时不断更新最大容量的数值,直到两个指针指向同一位置。
移动原理: 初始指针的位置在x轴上的长度是最长的,但将指向较短线段的指针向内移动时,虽然x轴上的长度变短,却有可能因为指向的线段变长而使总容量变长。
整个过程只对数组进行了一次遍历,因此时间复杂度为O( n n n)。

Solution (Java)

双重循环:

class Solution {
    public int maxArea(int[] height) {
        int N = height.length;
        int water, max = 0;
        for(int i = 0; i < N; i++){
            for(int j = i+1; j < N; j++){
                water = Math.min(height[i], height[j]) * (j-i);
                max = Math.max(max, water);
            }
        }
        return max;
    }
}

双指针:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值