Leetcode -盛最多水的容器

这篇博客探讨了两种解决LeetCode问题'Container With Most Water'的算法:暴力法和双指针法。暴力法使用两层循环,时间复杂度为O(n^2);而双指针法通过首尾指针迭代,将时间复杂度降低到O(n)。这种方法提高了效率,减少了不必要的计算。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode-cn.com/problems/container-with-most-water/
面积计算:area = (j-i) * min(height(i), height(j))
方法一:暴力法,两层循环,时间复杂度O(n^2)

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

方法二:首尾指针法,时间复杂度O(n)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值