【LeetCode】330. 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.

思路

设置一个变量maxp,记录可以达到的最大值,当maxp大于n时就输出patches数目。因为数组nums是有序的,所以当maxp+1仍然小于nums当前未利用的最小数字时,他们之间是有一个gap的,需要打patch。举例来说,maxp=3,nums第一个数是8,所以需要打patch。patch=maxp+1。所以打完patch后的maxp=maxp+patch=2maxp+1=7。maxp+1==8了,所以第一个数我们可以利用上,所以maxp=15了。

代码

class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        int maxp=0,i=0,patches=0;
        while (maxp<n&&maxp<pow(2,30)){
            if (i<nums.size()){
                while (maxp+1<nums[i]&&maxp<n){
                    maxp = 2*maxp+1;
                    patches++;
                }
                maxp += nums[i++];
            }
            else{
                maxp = maxp*2+1;
                patches++;
            }

        }
        return patches+(maxp<n?1:0);
    }
};

陷阱

当maxp很大时,乘以2+1会溢出,所以在前边判断循环条件时加了一个限制条件,当maxp大于pow(2,30)就不用再计算,直接+1就可以覆盖所有的int数

Hot解法

思路大致一样,但是它用了miss来表示[0,n]中我们缺失的最小数,这样我们就不用maxp+1进行比较了,而且不用判断是否溢出,这一点我表示很诧异。为什么不需要判断miss += miss是否溢出了呢。

int minPatches(vector<int>& nums, int n) {
    long miss = 1, added = 0, i = 0;
    while (miss <= n) {
        if (i < nums.size() && nums[i] <= miss) {
            miss += nums[i++];
        } else {
            miss += miss;
            added++;
        }
    }
    return added;
}

你可能感兴趣的:(LeetCode)