★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mffjrscq-hz.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Example 1:github
Input: nums = , n = Output: 1 Explanation: Combinations of nums are , which form possible sums of: . Now if we add/patch to nums, the combinations are: . Possible sums are , which now covers the range . So we only need patch.[1,3]6[1], [3], [1,3]1, 3, 42[1], [2], [3], [1,3], [2,3], [1,2,3]1, 2, 3, 4, 5, 6[1, 6]1
Example 2:數組
Input: nums = , n = Output: 2 Explanation: The two patches can be . [1,5,10]20[2, 4]
Example 3:微信
Input: nums = , n = Output: 0[1,2,2]5
給定一個已排序的正整數數組 nums,和一個正整數 n 。從 [1, n]
區間內選取任意個數字補充到 nums 中,使得 [1, n]
區間內的任何數字均可以用 nums 中某幾個數字的和來表示。請輸出知足上述要求的最少須要補充的數字個數。ui
示例 1:spa
輸入: nums = , n = 輸出: 1 解釋: 根據 nums 裏現有的組合 ,能夠得出 。 如今若是咱們將 添加到 nums 中, 組合變爲: 。 其和能夠表示數字 ,可以覆蓋 區間裏全部的數。 因此咱們最少須要添加一個數字。[1,3]6[1], [3], [1,3]1, 3, 42[1], [2], [3], [1,3], [2,3], [1,2,3]1, 2, 3, 4, 5, 6[1, 6]
示例 2:code
輸入: nums = , n = 輸出: 2 解釋: 咱們須要添加 。 [1,5,10]20[2, 4]
示例 3:orm
輸入: nums = , n = 輸出: 0[1,2,2]5
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 }