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.

一刷
题解:
让miss表示[0-n]中最小的一个可能miss掉的sum, 那么我们可以达到[0, miss)所有的sum。
对于当前的num, 如果num<=miss, 那么就可以组成[0, miss+num)的所有sum, 如果不能,则把miss加入其中。

int minPatches(vector<int>& nums, int n) {
    long miss = 1, added = 0, i = 0;
    while (miss <= n) {
        if (i < nums.size() && nums[i] <= miss) {
            miss += nums[i++];
        } else {
            miss += miss;
            added++;
        }
    }
    return added;
}

二刷

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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 前些天在为一些事烦闷着,一些不想做却又貌似不得不去做的事。 有些疲惫,却又不知是该前进还是停留。 人渐...
    聆云一甜蜜阅读 3,811评论 4 8
  • 叮······叮······叭 ·······叭··········我们是踏上乡间小路还是繁华的城市的夜景。 睁开...
    吾心如月阅读 1,924评论 0 0
  • 弘一大师将人的生活分作三层 一层是物质生活 二层是精神生活 三层是灵魂生活 物质生活指人们的衣食住行; 精神生活通...
    春花秋诗阅读 5,405评论 6 11
  • 白茫茫飞雪打在脸上 絮絮叨叨在说什么 路灯太刺眼 却忍不住让人发笑 好美的雪 还有那无人踩过的路 低头看看自己 雪...
    8b3631d5cf0a阅读 3,800评论 0 0