【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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值