【问题标题】:How to find two missing values in an array? [duplicate]如何在数组中找到两个缺失值? [复制]
【发布时间】:2012-12-03 21:30:03
【问题描述】:

可能重复:
Easy interview question got harder: given numbers 1..100, find the missing number(s)

求职面试问题。 假设我们有一个大小为 N-2 的数组,所有值都从 1 到 N,除了两个缺失值。 (N>0)

需要一种算法来查找两个缺失的数字,该算法只遍历数组一次。

【问题讨论】:

    标签: c++ arrays algorithm


    【解决方案1】:
    // Receiving array with values from 1 to N (NOT 0 to N-1)
    // N is max value & # of values, NOT size of arr (arr is in size N-2)
    void Find2Numbers(unsigned arr[], size_t N, unsigned & n1, unsigned & n2)
    {
        unsigned sum = N*(N+1)/2;  // sum of elements
        double pro = 1;  // Products will be calculated within the loop, because fact(N) can be very large
    
        for(size_t i = 0 ; i < N-2 ; i++)
        {
            pro *= (i+1);  // mult by i+1 to get factorial
            pro /= arr[i];  // divide by arr[i] to find n1*n2
            sum -= arr[i];
        }
        pro *= (N-1)*N;  // 2 missing indexes, as arr is missing 2 elements
        // sum = n1+n2
        // pro = n1*n2  =>
        n1 = (sum+sqrt(sum*sum-4*pro))/2;
        n2 = (sum-sqrt(sum*sum-4*pro))/2;
    }
    

    【讨论】:

    • @NPE - 你乘法然后你立即除法。
    • @NPE - 我已经运行了 N=10,000 并且它工作得很好。我会检查它是否为 100,000,但 sum=N*(N+1) 溢出,因此您可以获取代码并更改它以计算循环内的总和,以查看是否适用于非常大的 N。
    • @LeonidVolnitsky:哦,我错过了分区。问题撤回。
    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2020-07-03
    • 2019-12-01
    • 1970-01-01
    • 2021-12-24
    • 2019-11-06
    相关资源
    最近更新 更多