LeetCode 330. 按要求补齐数组

Posted 数据结构和算法

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 330. 按要求补齐数组相关的知识,希望对你有一定的参考价值。

在这里插入图片描述

想看更多算法题,可以扫描上方二维码关注我微信公众号“数据结构和算法”,截止到目前我已经在公众号中更新了500多道算法题,其中部分已经整理成了pdf文档,截止到目前总共有1000多页(并且还会不断的增加),可以在公众号中回复关键字“pdf”即可下载。

在这里插入图片描述
在这里插入图片描述

public int minPatches(int[] nums, int n) {
    //累加的总和
    long total = 0;
    //需要补充的数字个数
    int count = 0;
    //访问的数组下标索引
    int index = 0;
    while (total < n) {
        if (index < nums.length && nums[index] <= total + 1) {
            //如果数组能组成的数字范围是[1,total],那么加上nums[index]
            //就变成了[1,total]U[nums[index],total+nums[index]]
            //结果就是[1,total+nums[index]]
            total += nums[index++];
        } else {
            //添加一个新数字,并且count加1
            total = total + (total + 1);
            count++;
        }
    }
    return count;
}

在这里插入图片描述

public int minPatches(int[] nums, int n) {
    //累加的总和
    long total = 1;
    //需要补充的数字个数
    int count = 0;
    //访问的数组下标索引
    int index = 0;
    while (total <= n) {
        if (index < nums.length && nums[index] <= total) {
            //如果数组能组成的数字范围是[1,total),那么加上nums[index]
            //就变成了[1,total)U[nums[index],total+nums[index])
            //结果就是[1,total+nums[index])
            total += nums[index++];
        } else {
            //添加一个新数字,并且count加1
            total <<= 1;
            count++;
        }
    }
    return count;
}

以上是关于LeetCode 330. 按要求补齐数组的主要内容,如果未能解决你的问题,请参考以下文章