一个求职面试题。假设我们有一个大小为 N-2 的数组,所有值都从 1 到 N,除了两个缺失值。(N>0)
需要一种用于查找两个缺失数字的算法,该算法仅遍历数组一次。
一个求职面试题。假设我们有一个大小为 N-2 的数组,所有值都从 1 到 N,除了两个缺失值。(N>0)
需要一种用于查找两个缺失数字的算法,该算法仅遍历数组一次。
// 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;
}