【LeetCode】11. Container With Most Water 解题报告

这篇博客介绍了LeetCode第11题《Container With Most Water》的解题报告,讨论如何找到两个非负整数,构成容器以容纳最多的水。文章解释了问题背景,给出了两种解决方案:一种是双重循环的直接解法,虽然简单但时间复杂度较高;另一种是采用双指针技巧,从两端向中间移动,以线性时间复杂度找到最优解。

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


转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937


Subject

出处:https://leetcode.com/problems/container-with-most-water/


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.


Explain

给定n个非负的整数a1,a2 ……an, 去哦中每个代表一个点坐标(i, ai)。一共n个垂直线段。找到两个线段,与X轴形成一个容器,使其能剩最多的水。

其实就是找到这两条线段之后,用最短的线段的长度 * 两个线段之间的距离。


Solution

solution 1

通过嵌套循环来做。很明显,这是比较笨的方法,也是最容易想到的方法。

时间复杂度也就是o(n²)了。

    /**
     * 时间复杂度o(n²)
     * 
     * @param height
     * @return
     */
    public int maxArea1(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int result = 0;
        int temp = 0;
        for (int i = 0; i < height.length; i++) {
            for (int j = i + 1; j < height.length; j++) {
                temp = (j - i) * Math.min(height[i], height[j]);
                if (temp > result) {
                    result = temp;
                }
            }
        }
        return result;
    }

solution 2

通过两个“指针”,分别指向头和尾。

分别往中间移动,
当 “左指针” 指向的线段长度小于“右指针”指向的线段长度,则移动 “左指针” 。
反之,移动“右指针”。

    /**
     * 
     * @param height
     * @return
     */
    public int maxArea2(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int left = 0;
        int right = height.length - 1;
        int result = 0;
        int temp = 0;

        while (left < right) {
            temp = (right - left) * Math.min(height[left], height[right]);
            result = Math.max(result, temp);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }

        return result;
    }

时间复杂度是o(n)。


bingo~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值