330. 按要求补齐数组

给定一个已排序的正整数数组和一个正整数n,需要找到最少需要添加多少个元素,使得所有在[n, m]范围内的数都能通过数组中的元素组合得出。采用贪心策略,维护当前序列最大值,逐步判断是否需要添加当前最大值+1。" 86744569,5030223,项目思维与产品思维:关注输出还是结果?,"['产品运营', '项目管理']
摘要由CSDN通过智能技术生成

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,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。

思路: 贪心策略

维护一个当前序列所能得到的最大值max,最开始为0,遍历数组

判断当前值cur是否小于等于max+1,如果是,max+=cur,数组指针往后移动一位.

如果当前值大于max+1,则需要向数组中添加max+1,更新max所能达到的距离为2*max+1.数组指针不变

重复以上过程直到m>=n.

Code:

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

                maxnum+=nums[i];
                i++;
            }
            else{
               // cout<<count<<' ' <<maxnum<<endl;
                maxnum+=(maxnum+1);
                count++;
            }
        }
        return count;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值