Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 1.84 KB

330.md

File metadata and controls

35 lines (25 loc) · 1.84 KB

330 Patching Array

Description

link


Solution

Think about this example: nums = [1, 2, 3, 9]. We naturally want to iterate through nums from left to right and see what we would discover. After we encountered 1, we know 1...1 is patched completely. After encountered 2, we know 1...3 (1+2) is patched completely. After we encountered 3, we know 1...6 (1+2+3) is patched completely. After we encountered 9, the smallest number we can get is 9. So we must patch a new number here so that we don't miss 7, 8. To have 7, the numbers we can patch is 1, 2, 3 ... 7. Any number greater than 7 won't help here. Patching 8 will not help you get 7. So we have 7 numbers (1...7) to choose from. I hope you can see number 7 works best here because if we chose number 7, we can move all the way up to 1+2+3+7 = 13. (1...13 is patched completely) and it makes us reach n as quickly as possible. After we patched 7 and reach 13, we can consider last element 9 in nums. Having 9 makes us reach 13+9 = 22, which means 1...22 is completely patched. If we still did't reach n, we can then patch 23, which makes 1...45 (22+23) completely patched. We continue until we reach n.

  • miss 代表当前缺失的数字
  • 1 如果存在nums i小于当前miss,则miss + nums[i]范围内的数均可以满足,见上面detail
  • 2 如果nums[i]大于当前miss或者nums已经到了尽头,那么Miss不断翻倍(patch自己)不断逼近n达到目的

Code

Complexity T : O((n+m)^2)

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