出题:
有一组数字,从1到n,从中减少了3个数,顺序也被打乱,放在一个n-3的数组里
请找出丢失的数字,最好能有程序,最好算法比较快
假设n=10000
答案:
我的思路剖析:
1.申请一个数组,长度为n,每个字节初始化为1
2.遍历待检查的数组,取出值作为索引对应之前申请的数组相应位置为0
3.遍历第1步里面的数组,如果相应位为1则把该数组下标加1后添加到结果集中
以上就是一个最容易理解的思路,不过这个还可以进一步改进。
算法改进:
我们可以用位向量来存储域(这个域就是1到n),这样我们申请 (n+7)/8 *8bit 的空间就好了,因为C里面没有bit的直接I/O,所以我们通过位运算来实现。具体看了代码就明白了。
代码如下:
[cpp] view plaincopyprint?
/*
result:存放结果集的数组
dest:提供的待检查的数组
destLength:待检查的数组的长度
n:完整域
*/
int func(int* result,int dest[],int destLength,int n){
int resultCount =0;
int BitCharLength = (n+7)/8;
int i;
if ((n-destLength)==0) {//待检查数组长度等于域长度
return -1;
}
char* BitChar = (char*)malloc(BitCharLength*sizeof(char));
if (BitChar==NULL) {//申请位向量空间失败
return -2;
}
result = (int*)malloc((n-destLength)*sizeof(int));
if (result==NULL) {//申请结果集空间失败
return -3;
}
for (i = 0;i<(n+7)/8; i++) {//位向量所有位都置1
BitChar[i] = 127;
}
for (i = 0; i<destLength; i++) { //把dest[i]在BitChar中对应的bit置为0
BitChar[dest[i]>>3] &=~(1<<(dest[i] & 7));
}//这个完成以后存在的bit位全置0了,不存在的还是1;
for (i = 0; i<(n+7)/8; i++) {//把BitChar[i]中为一的位对应的索引写到result中
if ((BitChar[i] & 1) != 0) {//00000001
resultCount++;
result[resultCount]= 8*i+1;
}
if ((BitChar[i] & 2) != 0) {//00000010
resultCount++;
result[resultCount]= 8*i+2;
}
if ((BitChar[i] & 4) != 0) {//00000100
resultCount++;
result[resultCount]= 8*i+3;
}
if ((BitChar[i] & 8) != 0) {//00001000
resultCount++;
result[resultCount]= 8*i+4;
}
if ((BitChar[i] & 16)!= 0) {//00010000
resultCount++;
result[resultCount]= 8*i+5;
}
if ((BitChar[i] & 32)!= 0) {//00100000
resultCount++;
result[resultCount]= 8*i+6;
}
if ((BitChar[i] & 64)!= 0) {//01000000
resultCount++;
result[resultCount]= 8*i+7;
}
if ((BitChar[i] &128)!= 0) {//10000000
resultCount++;
result[resultCount]= 8*i+8;
}
if (resultCount == (n - destLength)) {
return resultCount;
}
}
return resultCount;
}