There is an array of size 50 that is expected to contain all the numbers from 1 to 50
(every number occuring only once). But there is one number in the array that does not
satisfy this condition i.e. one number is either duplicate or outside 1 to 50 range.
方法3:(有点小错误)(和上个思路类似,但是,有点递推的思想)
(every number occuring only once). But there is one number in the array that does not
satisfy this condition i.e. one number is either duplicate or outside 1 to 50 range.
Find the correct number that is missing in the array
方法1:
设原数组是a[],设非法的那个数是y,缺少的数是x
1+2+...+50 - sum(a) = y -x
1^2+ 2^2 + ... + 50^2 - (a[0]^2 + ...+a[49]^2) = y^2 - x^2
可以计算出x
将数放到其应该在的地方
方法2(思想就是在位置i将其放在正确的位置):
int findMissing(int a[], int n)
{
int i;
for(i = 0; i < n; i++) {
while(a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i])//短短几句话,自己写错了好多。1. 用if 不用while, 不会把数字放在其正确的位置;2. a[i] != i+1, 如果遇到重复的数字,可能会进入死循环
swap(a[i], a[a[i] - 1]);
}
for(i = 0; i < n; i++)
if(a[i] != i + 1)
return i + 1;
return -1;
}
方法3:(有点小错误)(和上个思路类似,但是,有点递推的思想)
int FindDup(int a[], int n)
{
assert(a && n > 0);
for (int i = 0; i < n; i++)
{
if (i + 1 == a[i])
continue;
int nTmp = a[i];
while (i + 1 != nTmp)
{
if (nTmp < 1 || nTmp > n)
return -1;
if (nTmp == a[nTmp - 1])
return nTmp;
int x = a[nTmp - 1];
a[nTmp - 1] = nTmp;
nTmp = x;
}
}
return -1;
}