LeetCode 330. Patching Array

330. Patching Array

一、问题描述

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-7全部都能获取。那么再加一个5,最大能获取为7+5=12,那么是不是[8,12]也就全部都能获取了那?答案是:是的! 想明白这个你就差不多了。
  • 原来的区间是[1,7] 现在多了一个5,我们把5加到这个区间上,相当于可以获取[6,12] 然后 [1,7] U [6,12] = [1, 12] 不但能到12,而且6和7还有两种办法达到,一种是使用了5的,一种是没有使用5的。
  • 再来看,假如现在给你一个7 最大能到7+7=14 那么是不是[1,14]全部能到那?聪明的你肯定想到了:是的。[1,7] U [8,14] = [1,14] 注意这时候交点没有重叠了,正好是7到8.为什么会这样那,因为新加进来的数字加上1 正好是原来最大值的下一个(7+1)。
  • 再来看,假如现在给你一个8,最大能到7+8 = 15,那么是不是[1,15]全部都能到那?如果你还回答是,那么就错了。原来是区间[1,7] 我们在区间的基础上都加上8,相当于是向右移动8个单位长度,新区间是[1+8, 7+8]=[9,15] 看出来了把?少了一个8,没有连上。为什么没有连上那,原因就是区间的左端向右移动的太多了,已经超出了原来的右端,所以连不上了。这个临界点,就是原区间右端的值。
  • 在程序中,我们用miss来记录区间右端这个值。如果nums[i] <= miss 那么就直接加到原区间上,miss+=nums[i] 如果nums[i] > miss 这时候miss += miss 保证区间移动的连续性。miss > n 的时候退出。
class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        long miss = 1, ret = 0, i = 0, length = nums.size();
        while (miss <= n){
            if(i < length && nums[i] <= miss){
                miss += nums[i];
                i++;
            }else{
                miss += miss;
                ret++;
            }
        }
        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值