【问题标题】:from number of possible pairs get the size of the original array从可能的对数中获取原始数组的大小
【发布时间】:2018-08-01 01:06:05
【问题描述】:

我有这个功能

public int numberOfPossiblePairs(int n)
{
        int k=2;
        if (k>n-k) { k=n-k;}  
        int b=1;
        for (int i=1, m=n; i<=k; i++, m--)
            b=b*m/i;
        return b;
} 

它会从给定数量的项目中获取您可以制作的配对数量,例如,如果您有一个包含 1000 件商品的数组,您可以制作 499,500 对。但我真正需要的是相反的。换句话说,一个函数将 499500 作为参数,并返回 1000 作为可以产生那么多对的唯一项目的原始数量。 (如果它还可以处理不完美的数字,例如 499501,这将是一个奖励,其中没有多少独特的项目可以产生那么多独特的配对,但它仍然会返回 1000 作为最接近的数字,因为它产生了 499500 配对。)

我意识到我可以逐步循环 numberOfPossiblePairs() 直到我看到我正在寻找的数字,但似乎应该有一种算法方法来做到这一点,而不是像那样强制它。

【问题讨论】:

    标签: combinations


    【解决方案1】:

    您的问题归结为一点代数,可以在O(1) 时间内解决。我们首先注意到您的函数没有给出对的排列数,而是给出对的组合数。无论如何,可以轻松更改以下逻辑以适应排列。

    我们首先编写选择k的组合数的公式。

    设置 n = 1000r = 2 给出:

    1000! / (2!(998)!) = 1000 * 999 / 2 = 499500
    

    就像numberOfPossiblePairs(1000) 所做的那样。

    继续我们的练习,对于我们的示例,我们有 r = 2,因此:

    total = n! / ((n - 2)! * 2!)
    

    我们现在简化:

    total = (n * (n - 1)) / 2
    
    total * 2 = n^2 - n
    
    n^2 - n - 2 * total = 0
    

    现在我们可以应用二次公式来求解n

    这里我们有 x = na = 1b = -1c = -2 * 总计 其中给出:

    n = (-(-1) +/- sqrt(1^2 - 4 * 1 * (-2 * total))) / 2
    

    由于我们只对正数感兴趣,因此我们排除了负数解决方案。在代码中我们有类似的东西(注意,看起来 OP 正在使用 Java,我不是这里的专家......以下是 C++):

    int originalNumber(int total) {
        int result;
        result = (1 + std::sqrt(1 - 4 * 1 * (-2 * total))) / 2;
        return result;
    }
    

    至于如果结果不是整数则返回最接近的值的额外问题,我们可以在强制转换为整数之前简单地将结果四舍五入:

    int originalNumber(int total) {
        int result;
        double temp;
        temp = (1 + std::sqrt(1 - 4 * 1 * (-2 * total))) / 2;
        result = (int) std::round(temp);
        return result;
    }
    

    现在,当传递500050 之类的值时,实际结果为1000.55,上面将返回1001,而第一个解决方案将返回1000

    【讨论】:

    • 太棒了!谢谢约瑟夫伍德!我修复了您提到的关键字,这是您在 java public static int originalNumber(int total) { int result; 中的公式双倍温度; temp = (1 + Math.sqrt((1 - 4 * 1 * (-2 * total)))) / 2;结果=(int)温度;返回结果; }
    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2015-02-27
    相关资源
    最近更新 更多