可能重复:
Easy interview question got harder: given numbers 1..100, find the missing number(s)
求职面试问题。 假设我们有一个大小为N-2的数组,除了两个缺失值之外,所有值都从1到N。 (N 0)
需要一种用于查找两个缺失数字的算法,该算法仅遍历数组一次。
答案 0 :(得分:5)
// 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;
}