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
分析
这一题的解法挺巧妙的。很难写出来一个比较精简的答案。我们分析一下[1,2,3,5]最大能组成多大的数,首先找1,发现1在数组中,那么接下来找2,发现2也在数组中,那么接下来[1,2]其实就可以得到3。那么数组中也有个3,那么最大其实就可以得到6。那么数组中5其实还没有使用,那么最大就可以得到11。
所以假设[1, k]我们都已经找到了,而数组中有一个nums[m]我们还没有用到,那么接下来就可以直接跳到nums[m] + k;然后继续看nums数组中有没有< nums[m] + k的没有用到的数。
如果[1, k]已经找到,nums中没有<= k+1的数值了,那么就需要填一个数,然后就直接跳到了k + 1 + k了。
Code
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int len = nums.size();
int cnt = 0;
long long miss = 1;
int i = 0;
while (miss <= n)
{
if (i < len && nums[i] <= miss)
{
miss += nums[i];
i ++;
}
else
{
cnt ++;
miss = miss << 1;
}
}
return cnt;
}
};
运行效率
Runtime: 8 ms, faster than 95.57% of C++ online submissions for Patching Array.
Memory Usage: 9.2 MB, less than 11.25% of C++ online submissions forPatching Array.