[leetcode] 330. Patching Array 解题报告

题目链接: https://leetcode.com/problems/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.


思路: 一个贪心的算法, 因为数组是排好序的, 因此我们从左到右遍历数组, 并且维护一个到当前为止最大可以到达的值, 如果当前数组的值比这个最大值大的话说明我们无法合成这个值, 需要补贴一个数, 然后加上补贴的这个数更新为新的最大可到达的值.举个栗子: nums = [1, 5, 10]n = 20

最初始状态, 我们能够cover的是小于1的数, 因此第一个遇到1正好可以cover下一个数, 因此不需要补贴, 这样我们可以更新最大可以cover的值为1*2 = 2以内的数.

第二个数组值为5, 而现在我们只能cover 2以内的数, 因此需要补贴一个2, 最大值变成了2*2 = 4. 也就是下次我们可以合成4以内的数.

然后仍然看数组的值5, 添加了2以后依然无法到达5, 因此我们需要再补贴一个值4, 之后我们最大可以到达的数变成了8以内的数.

在一次看数组值5, 这个5在可以cover的数范围内了, 因此可以遍历数组的下一个值了.而多了一个5之后我们可以到达的最大值变成了8+5 =13以内的值了 

下一个数组值为10, 依然在我们能够cover的值之内, 因此不需要补贴, 然后有了10之后能够cover的值的范围变成了13+10 =23 > 20, 因此我们只要补贴两个值即可.

代码如下:

class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        long sum = 1, ans = 0, index = 0;
        while(sum <= n)
        {
            if(index>=nums.size() || sum<nums[index]) sum*=2, ans++;
            else sum += nums[index++];
        }
        return ans;
    }
};
参考: https://leetcode.com/discuss/83272/share-my-thinking-process
















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值