LeetCode 330. Patching Array(数组补丁)

给定一个已排序的正整数数组nums和一个整数n,通过添加/补丁元素到数组,使得数组能形成范围[1, n]内任意数的和。返回所需的最少补丁数量。本文通过举例说明问题,并探讨了如何找到最小补丁数量的方法。" 5979037,922805,电路图绘制指南,"['嵌入式硬件', '电路设计', '电子工程']

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

原题网址:https://leetcode.com/problems/patching-array/

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:
nums = [1, 3]n = 6
Return 1.

Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:
nums = [1, 5, 10]n = 20
Return 2.
The two patches can be [2, 4].

Example 3:
nums = [1, 2, 2]n = 5
Return 0.

方法:假设对于某个正整数m,能够组合出 [1,m),则如果我们补充一个数字m,意味着能够组合出 [1,m) U m U [1+m, m+m) = [1, m+m)。那么现在的问题是,究竟是需要打补丁,还是从nums中取出数字?我们设置一个指针i,表示nums中最小的未使用的下标元素。即nums[0],nums[1],...,nums[i-1]已经使用过,而nums[i]未使用,这意味着nums[0]~nums[i-1]加上必要的补丁数字,能够组合出 [1,m),如果nums[i]<=m,则引入nums[i],新的组合是 [1,m) U nums[i] U [1+nums[i], m+nums[i])。如果nums[i]==m,则新的组合等价于[1, m+nums[i]);如果nums[i]<m,则新的组合同样等价于 [1, m+nums[i])。

此题我没有做出来,参考网上的:https://leetcode.com/discuss/82822/solution-explanation


public class Solution {
    public int minPatches(int[] nums, int n) {
        int patches = 0;
        long missing = 1;
        int i = 0;
        while (missing <= n) {
            if (i < nums.length && nums[i] <= missing) {
                missing += nums[i++];
            } else {
                missing += missing;
                patches ++;
            }
        }
        return patches;
    }
}

另一种实现:

public class Solution {
    public int minPatches(int[] nums, int n) {
        long max = 0;
        int patch = 0;
        int i=0;
        while (max<n) {
            while (i<nums.length && nums[i]-1 <= max && max < n) max += nums[i++];
            if (max >= n) break;
            max += max + 1;
            patch ++;
        }
        return patch;
    }
}

再一种实现:

public class Solution {
    public int minPatches(int[] nums, int n) {
        long max = 0;
        int patch = 0;
        int i=0;
        while (max<n) {
            if (i<nums.length && nums[i]-1 <= max) max += nums[i++];
            else {
                max += max + 1;
                patch ++;
            }
        }
        return patch;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值