[LeetCode] 330. Patching Array

42 篇文章 0 订阅
37 篇文章 0 订阅

题目链接: https://leetcode.com/problems/patching-array/

Description

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.


解题思路

设置一个 miss 变量表示我们现在未覆盖的最小的数字。因为我们要满足从 1~n 都覆盖,所以设 miss 初始值为 1。
开始循环时,分两种情况考虑,一种是数组里面的数字还没有全都用上,另一种是数组里的数字都用完了。

标注: min 表示数组中未使用过最小的数字

  1. 数组里的数字没全用上
    比较需要的数字 miss 和数组里没有用的数字中最小的,有三种情况
    • miss 更小
      这时候数组中没有一个组合可以满足需要的值,需要插入该值,即插入 miss ,这时候覆盖的范围变成了 [1, miss × 2 - 1]。更新 miss 为未覆盖的值,即 miss = miss × 2。
    • miss 更大
      当前可以表示的范围为 [1, miss - 1],再加上数组里没有使用的最小的值,就可以表示范围 [1, miss + min - 1]。
    • 一样大
      miss 更大的情况。
  2. 数组里的数字全都用过
    这时候只能通过插值来满足题意,与第一种情况类似。每次插入的值都为 miss,能表示的范围更新为 [1, miss × 2 - 1],再更新 miss 为未覆盖的值,即 miss = miss × 2。

循环直到未覆盖的最小数字 miss 大于我们需要覆盖到的值 n 时终止。

上述思路,整理转化为代码如下。

Code

int minPatches(vector<int>& nums, int n) {
    int ans = 0;
    int pos = 0;
    int length = nums.size();
    long miss = 1;

    while (miss <= n) {
        if (pos < length && nums[pos] <= miss) {
            miss += nums[pos++];
        } else {
            ans++;
            miss <<= 1;
        }
    }

    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值