330. Patching Array 给数组添上元素,使得满足存在所有1~n元素

来源:互联网 发布:淘宝限时促销关键词 编辑:程序博客网 时间:2024/05/20 06:09

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.


解答:

1.我的想法  暴力

对于给定一个数组,元素之间进行相加,然后进行排序,从头到尾进行遍历,发现不存在的元素就加入,但是时间复杂度太高了,超时了,,,,

class Solution {public:void add(vector<int>& s, int num, int n){    int len = s.size();    for(int it = 0; it < len; it++){        int res = s[it] + num;        if(res <= n)            s.push_back(res);    }    s.push_back(num);}int minPatches(vector<int>& nums, int n) {    vector<int>s;    int count = 0;    if(nums.size() > 0){        s.push_back(nums[0]);        for(int i = 1; i< nums.size(); i++)            add(s, nums[i], n);    }    else{        add(s, 1, n);        count++;    }    sort(s.begin(), s.end());    if(s.size() == n)        return 0;    while(true){        int maxn = 0;        for(int i = 1; i <=n; i++){            if(s[i-1] != i){                maxn = i;                break;            }        }        add(s, maxn, n);        count++;        sort(s.begin(), s.end());        s.erase(unique(s.begin(), s.end()),s.end());        if(s.size() == n)            break;    }    return count;}};



2.别人的解答  用贪心的方法

比如:开始时最大值为0,从num的第0个元素开始遍历

nums=[1 2 5 6 20], n = 50.

第一次时,若元素<= max+1,则将此元素加入max中;【1~1】


加入了1,则max=1,那么下一个要加入的就是2(max+1),如果下一个元素满足<=max+1,那么就把该元素加入,则此时的数组【1,2】中能达到的最大值max=3; 【1~13】


那么下一个要加入的就是4,但是此时4<5,说明数组里没有4,此时需要把4加入max,同时count++; 那么此时最大值max=3+4=7,数组中有【1,2,4】;【1~7】


下一个要加入的就是max+1=8,此时 5<8,可以把范围缩小为5+max=12=max;【1~12】


下一个要加入12+1=13,此时6<13,那么范围扩大为6+max=18;此时数组为【1,2,4,5,6】 【1~18】


下一个要加入的就是18+1=19,此时19<20,那么需要加入19,此时max=19+18=37,count++; 【1~37】


下一个要加入的是38,此时20<38,只需扩大范围20+37=57,到此57>n=50,程序结束。【1~57】


程序如下:


class Solution {public:    int minPatches(vector<int>& nums, int n) {        int cnt = 0, i = 0, len = nums.size();        long long maxnum = 0;        while(maxnum < n){            if(i < len && nums[i] <= maxnum + 1){                maxnum += nums[i];                i++;            }else{                maxnum += (maxnum + 1);                cnt++;            }        }        return cnt;    }};



0 0
原创粉丝点击