zoukankan      html  css  js  c++  java
  • 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:

    
    
    Input: nums = [1,3], n = 6
    Output: 1 
    Explanation:
    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:

    
    
    Input: nums = [1,5,10], n = 20
    Output: 2
    Explanation: The two patches can be [2, 4].
    
    
    

    Example 3:

    
    
    Input: nums = [1,2,2], n = 5
    Output: 0


    1
    class Solution { 2 public: 3 int minPatches(vector<int>& nums, int n) { 4 long miss = 1, added = 0, i = 0; 5 while (miss <= n) { 6 if (i < nums.size() && nums[i] <= miss) { 7 miss += nums[i++]; 8 } else { 9 miss += miss; 10 added++; 11 } 12 } 13 return added; 14 } 15 };

    开始以为是dp, 看了答案发现是贪心  差不多10行. 感觉全方面受到了打击.

    贪心算法是看懂了, 不过并没有搞懂为什么这样就是最少的解法呢...

    给数组加上数字, 以便于可以得到1-n所有数字的和. 并且要加入的数字最少.

    贪心策略就是从1开始扫描,缺哪个补哪个...

    根据作者的例子: https://leetcode.com/problems/patching-array/discuss/78488/Solution-%2B-explanation

    nums = [1, 2, 4, 13, 43] and n = 100;

    1,2,4可以得到1-7的和. 8没有了, 所以加上8.

    因为前三个数字可以得到1-7, 那么加上8之后,就有 1-15(7+8) 的和.

    但是注意一下, 1-15 里面的13 是原数组本来就有的, 所以实际上我们可以得到1-28(15+13).

    再检查原数组, 自13以后, 原数组没有包含任何一个属于1-28的数字, 此轮贪心结束了.

    第二轮贪心, 下一个数字是43, 比28大的多,因此加上29. 于是我们可以得到1-57(28+29). 

    原数组又包含了43, 所以实际上可以得到1-100(57+43). 结束

    一共添加了8,29 两个数字....简直卧槽

  • 相关阅读:
    连接APB1和APB2的设备有哪些
    STM32串口配置步骤
    gcc -o test test.c编译报错
    EmBitz1.11中将左边的目录弄出来
    c51
    c51跑马灯
    51 单片机 跑马灯2
    51 单片机 跑马灯
    spring注解注入:<context:component-scan>以及其中的context:include-filter>和 <context:exclude-filter>的是干什么的?
    Cookie和Session的作用和工作原理
  • 原文地址:https://www.cnblogs.com/lychnis/p/11298692.html
Copyright © 2011-2022 走看看