leetcode 330 Patching Array

原题链接:Patching Array - LeetCode

题目

Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the 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:

Input: nums = [1,3], n = 6
Output: 1
Explanation:
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:

Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].

Example 3:

Input: nums = [1,2,2], n = 5
Output: 0

思路

从最小的1开始考虑,如果数组的第一个数不是1,则必须补上1,这时能组合出[1,1]的数。
然后看下一个数,如果大于2,那么2就没有办法用数组里的数表示出来了,所以要补上2,这时能组合出[1, 3]的数;如果下一个数A小于等于2,则把A加入数组,可组合范围就变为[1, 1+A]。

算法

如果遍历到nums[i-1]时,已经可以组合出[1, x]的所有数字,根据nums[i]的值有以下两种情况:
a. 若nums[i]小于等于x+1,我们就把nums[i]加入数组,加入之后就可以组合出[1,x+nums[i]]的数字。
b. 若nums[i]大于x+1,因为把nums[i]加入后不能组合出x和nums[i]之间的数字,所以不能把nums[i]加入数组;这时就需要加入一个新的数字x+1,加入之后可以组合出[1, 2x+1]的数字。
以此类推,直到可组合范围是[1, n]为止。

代码实现

class Solution:
    def minPatches(self, nums: List[int], n: int) -> int:
        edge = 0
        i = 0
        res = 0
        while edge < n:
            if i < len(nums) and nums[i] <= edge + 1:
                edge += nums[i]
                i += 1
            else:
                edge = edge * 2 + 1
                res += 1
        return res

复杂度分析

时间复杂度:O(N)
空间复杂度:O(1)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值