• LeetCode 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.

    题解:

    定义一个miss, 表示[0,n]中目前最小不能表示的数,初始为1,为啥不为0呢,因为n=0没啥意义,直接返回0了。那么此时我们能表示的范围是[0, miss), 表示此时我们能表示0到miss-1的数.

    如果此时的num[i] <= miss,那么我们可以把我们能表示数的范围扩大到[0, miss+num[i]), i++; 如果num[i]>miss, 那么此时我们需要添加一个数,为了能最大限度的增加表示数范围, miss翻倍.

    给定nums = [1, 2, 4, 11, 30], n = 50. 我们需要让[0, 50]之间所有的数字都能被nums中的数字之和表示出来。

    首先使用1, 2, 4可能表示出0到7之间的所有数,表示范围为[0, 8), 但我们不能表示8, 因为下一个数字11太大了, 所以我们要在数组里加上一个8, 此时能表示的范围是[0, 16), 那么我们需要插入16吗,答案是不需要,因为我们数组有1和4, 可以组成5, 而下一个数字11, 加一起能组成16, 所以有了数组中的11, 我们此时能表示的范围扩大到[0, 27), 但我们没法表示27, 因为30太大了,所以此时我们给数组中加入一个27, 那么现在能表示的范围是[0, 54), 已经满足要求了,我们总共添加了两个数8和27,所以返回2即可。

    若是空数组{}, n = 7. 此时要返回3, 因为添加了三个数1,2,4.

    Time Complexity: O(max(logn, nums.length)). n 是[0,n]的范围上线. logn是因为一次翻两倍. 几次能翻到n. Space: O(1).

    AC Java:

     1 public class Solution {
     2     public int minPatches(int[] nums, int n) {
     3         long miss = 1; 
     4         int count = 0;
     5         int i = 0;
     6         while(miss <= n){
     7             if(i < nums.length && nums[i] <= miss){ //若是nums[i] <= miss, 就把miss提高到miss+nums[i]. i++
     8                 miss += nums[i++];
     9             }else{  //若是nums[i]>miss, 此时需要加一个数, miss翻倍, i不动.
    10                 miss <<= 1;
    11                 count++;
    12             }
    13         }
    14         return count;
    15     }
    16 }

    Reference: https://leetcode.com/discuss/82822/solution-explanation

    http://www.cnblogs.com/grandyang/p/5165821.html

  • 相关阅读:
    关于DISCUZ!NT发布的问题整理!
    javascript 文字滚动显示[zhuan ]
    Bot Framework Emulator应用与调试
    Bot Framework的简单实现
    命名空间在扩展方法中的妙用
    Error:Execution failed for task ':app:transformClassesWithDexForDebug"
    C#中WebApi接口传参不再困惑:传参详解
    贝塞尔曲线
    从枚举值获取对应的文本描述
    常用正则表达式收集
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5300647.html
Copyright © 2020-2023  润新知