[Leetcode Daily Notes] 330. Fill up the array as required (Python)

topic

Given a sorted array of positive integers nums, and a positive integer n. Select any number from the interval [1, n] and add it to nums, so that
any number in the interval [1, n] can be represented by the sum of certain numbers in nums. Please output the minimum number of digits that meet the above requirements.

Example 1:

Input: nums = [1,3], n = 6 Output: 1 Explanation: According to the existing combination [1], [3], [1,3] in nums,
1, 3, 4 can be obtained . Now if we add 2 to nums, the combination becomes: [1], [2], [3], [1,3], [2,3],
[1,2,3]. The sum can represent the numbers 1, 2, 3, 4, 5, 6, which can cover all the numbers in the interval [1, 6].
So we need to add at least one number.

Example 2:

Input: nums = [1,5,10], n = 20 Output: 2 Explanation: We need to add [2, 4].

Example 3:

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

Problem-solving ideas

how are you

Features of the filled array:

假设数组 arr添加一个元素即可覆盖 [1,n)内所有数字,那么添加的数字 mmm 一定满足m <= n。
假设数组 arr 可以覆盖 [1,n) 的所有数字,则给 arr内加元素 m:
    若m <= n,新数组可以覆盖[1, m + n) = [1, n) ∪ [m, m + n)内所有数字;

Greedy rule: For an array arr covering [1,n), adding the number n has the largest continuous expansion range (expanding to [1,2n)). Idea: Set an initial range [1,1), and finally calculate the minimum number that needs to be added by continuously confirming and expanding the range that the array can cover.

当i < len(nums)且nums[i] <= add时:不需要加入新数字,循环确认并更新数组可以覆盖的范围[1, add + nums[i]),直到找到大于确认范围 add 的 nums[i] 或索引越界。
否则:无法根据现有数字构建更大的连续范围,因此需要使用贪心策略向数组加入数字 add ,将数组从覆盖 [1,add) 扩容至可覆盖 [1,2add)。
直到确认的范围add > n,说明此时已经覆盖 [1,n] ,退出迭代并返回。

Code

class Solution:
    def minPatches(self, nums: List[int], n: int) -> int:
        patches, x = 0, 1
        length, index = len(nums), 0

        while x <= n:
            if index < length and nums[index] <= x:
                x += nums[index]
                index += 1
            else:
                x *= 2
                patches += 1
        
        return patches

Guess you like

Origin blog.csdn.net/qq_36477513/article/details/111884069