给定一个非递减数组,以及n,求最小添加几个元素能保证通过元素组合覆盖到1至n任意数

//  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.
public static int minPatches(int[] nums, int n) {
        long miss = 1;
        int added = 0, i = 0;
        while (miss <= n) {
            if (i < nums.length && nums[i] <= miss) {
                miss += nums[i++];
            } else {
                added++;
                miss += miss;
            }
        }
        return added;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容