zoukankan      html  css  js  c++  java
  • Patching Array

    引用原文:http://blog.csdn.net/murmured/article/details/50596403

    但感觉原作者的解释中存在一些错误,这里加了一些自己的理解

    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.

    该题的解题思路来源于网络,实际上是一个动态规划的算法题,不过规律稍微有点不好找,规律如下:

    设:sum为当前所能达到的最大的连续和,并已有已知的一个数字集合M,这个时候在集合M中插入一个数字num,有一下情景

    1:当num<=sum+1时,sum可以得到扩展sum=sum+num;

    2:当num>sum+1时,此时sum不可以直接扩展,因为此时由sum+num的到的范围并不是连续的,如{1,2,3} ,sum=6,如果此时插入一个数字8,集合变为{1,2,3,8}这个时候是得不到7这个和的,所以只能再插入一个数字,这个时候为了尽可能增加sum,并保持连续性,最好的选择是插入sum+1这个数字,插入后更新sum=sum*2+1;然后再把num和sum+1进行比较,进行相应的处理,直到sum达到所需要的值。

    由此可知,我们需要记录sum+1的值,假设n为我们的预期,那么当sum+1=n时,我们仍然要继续计算,因为这个时候sum=n-1,并没有达到我们的预期

    需要注意的点:集合中的数字是int型的,但是sum的值可能超出int的范围

  • 相关阅读:
    [置顶] 寻找数组中的值
    详解 Java 的八大基本类型,写得非常好!
    从入门到放弃的 Java 架构师面试题!
    通往大牛之路,百度Java面试题前200页!
    HTML与CSS简单页面效果实例
    JS面向对象
    JS瀑布流效果
    CSS常用操作-图片
    CSS常用操作-导航栏
    CSS常用操作-对齐
  • 原文地址:https://www.cnblogs.com/sqxw/p/5166075.html
Copyright © 2011-2022 走看看