330. Patching Array (C++实现)

来源:互联网 发布:mac图片文件夹在哪 编辑:程序博客网 时间:2024/05/21 21:00

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:
nums = [1, 3]n = 6
Return 1.

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:
nums = [1, 5, 10]n = 20
Return 2.
The two patches can be [2, 4].

Example 3:
nums = [1, 2, 2]n = 5

Return 0.

解题思路:

假设数组nums的“部分元素和”可以表示范围【1, total】内的所有数字,

那么向nums中添加元素add可以将表示范围扩充至【1, total + add】,其中add ≤ total+1,当且仅当add = total+1时取到范围上界[1, 2 * total)。若取add>total+1,则会出现断层,元素的和不能覆盖整个【1, total + add】。

若nums数组为空,则构造[1, n]的nums为[1, 2, 4, 8, ..., k],k为小于等于n的2的幂的最大值。

若nums数组非空,则扩展时利用nums中的已有元素,详见代码。

<span style="font-size:18px;">class Solution {public:    int minPatches(vector<int>& nums, int n) {        unsigned int curSum=0;//当前能表示的最大范围        int k=0;//当前已添加元素的个数,存储返回结果。        for(int i=0;i<nums.size();i++){            if(curSum>=n)return k;            if(nums[i]<=curSum+1)                curSum+=nums[i];            else {                curSum=2*curSum+1;                k++;                i--;            }        }        while(curSum<n){            curSum=2*curSum+1;            k++;        }        return k;    }};</span>


0 0
原创粉丝点击