Day7 盛最多水的容器

给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水

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

示例1:


输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例2:

输入:height = [1,1]
输出:1

示例3:

输入:height = [4,3,2,1,4]
输出:16

示例4:

输入:height = [1,2,1]
输出:2

提示:

  • n = height.length
  • 2 <= n <= 3 * 104
  • 0 <= height[i] <= 3 * 104

思路:

  • 面积=两点差值*两点最小值;由此可以通过左侧遍历获取最大值
  • 最简单的方法,一次就过但效率不行,官方解很NICE,当时考虑过,但没找到移到条件
package sj.shimmer.algorithm;

/**
 * Created by SJ on 2021/1/31.
 */

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

    public static int maxArea(int[] height) {
        if (height == null || height.length <= 1) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < height.length; i++) {
            for (int j = 1; j < height.length; j++) {
                int tempR = Math.min(height[i], height[j]) * (j - i);
                result = result < tempR?tempR:result;
            }
        }
        return result;
    }
}

官方解

  1. 双指针
    • 因为 面积=两点差值*两点最小值,从两边开始分别遍历,左右指针指向头尾,此时差值最大
    • 开始移动时即可将左右指针指向较小的点的指针向内移动(移动较大的会导致两个因数都变小,导致面积变小移动较小的会导致差值变小,但两点最小值可能变大,面积也有变大的可能
     public static int maxArea1(int[] height) {
            if (height == null || height.length <= 1) {
                return 0;
            }
            int left = 0;int right = height.length-1;
            int result = 0;
            while (left!=right){
                if (height[left]>height[right]) {
                    int tempR = height[right] * (right - left);
                    result = tempR>result?tempR:result;
                    right--;
                }else {
                    int tempR = height[left] * (right - left);
                    result = tempR>result?tempR:result;
                    left++;
                }
            }
            return result;
        }
    

    • 时间复杂度:O(N),双指针总计最多遍历整个数组一次。
    • 空间复杂度:O(1),只需要额外的常数级别的空间
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值