1. 程式人生 > >[Swift]LeetCode330. 按要求補齊陣列 | Patching Array

[Swift]LeetCode330. 按要求補齊陣列 | 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:

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

給定一個已排序的正整數陣列 nums,和一個正整數 n 。從 [1, n] 區間內選取任意個數字補充到 nums 中,使得 [1, n] 區間內的任何數字都可以用 nums 中某幾個數字的和來表示。請輸出滿足上述要求的最少需要補充的數字個數。

示例 1:

輸入: nums = [1,3], n = 6
輸出: 1 
解釋:
根據 nums 裡現有的組合 [1], [3], [1,3],可以得出 1, 3, 4。
現在如果我們將 2 新增到 nums 中, 組合變為: [1], [2], [3], [1,3], [2,3], [1,2,3]。
其和可以表示數字 1, 2, 3, 4, 5, 6,能夠覆蓋 [1, 6] 區間裡所有的數。
所以我們最少需要新增一個數字。

示例 2:

輸入: nums = [1,5,10], n = 20
輸出: 2
解釋: 我們需要新增 [2, 4]

示例 3:

輸入: nums = [1,2,2], n = 5
輸出: 0

52ms
 1 class Solution {
 2     func minPatches(_ nums: [Int], _ n: Int) -> Int {
 3         
 4         var miss = 1
 5         var res = 0
 6         var i = 0
 7         let l = nums.count
 8         while miss <= n {
 9             if i < l && nums[i] <= miss {
10                 miss += nums[i]
11                 i+=1
12             }else {
13                 miss <<= 1
14                 res += 1
15             }
16         }
17         return res
18     }
19 }