您的位置:首页 > 其它

找出数组{1,2,3,4,...N-1}中出现的唯一重复数

2016-01-17 10:15 309 查看
异或法:

/*
找出数组{1,2,3,4,...N-1}中出现的唯一重复数

*/

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int xor_findDup(int* a,int count)
{
int i = 0;
int temp = 0;
for(i=0;i<count;i++)
{
temp =  temp ^ a[i];
}
for(i=1;i<count;i++)
{
temp = temp ^ i;
}
return temp;
}

int main(int argc, char *argv[])
{
int a[]={1,3,2,4,2};
int length = sizeof(a)/sizeof(int);

cout << "Duplication is : " << xor_findDup(a,length) << endl;
return 0;
}


2.位图法

/*
找出数组{1,2,3,4,...N-1}中出现的唯一重复数

*/

#include <iostream>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int xor_findDup(int* a,int count)
{
int i = 0;
int temp = 0;
int* tempArray = (int*) malloc(sizeof(int)*(count));
for(i=0;i<count;i++)
{
tempArray[i] = 0;
}
for(i=0;i<count;i++)
{
if(tempArray[a[i]]==0)
{
tempArray[a[i]] = 1;
}
else
{
temp = a[i];
return a[i];
}
}
return temp;
}

int main(int argc, char *argv[])
{
int a[]={1,3,1,4,2};
int length = sizeof(a)/sizeof(int);

cout << "Duplication is : " << xor_findDup(a,length) << endl;
return 0;
}


上面的都有额外的开销

1.Hash法

/*
找出数组{1,2,3,4,...N-1}中出现的唯一重复数

*/

#include <iostream>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int xor_findDup(int* a,int count)
{
int i = 0;
for(i=0;i<count;i++)
{
if(a[i]>0)
{
if(a[a[i]]>0)
{
a[a[i]] = - a[a[i]];
}
else
{
return a[i];
}
}
else
{
if(a[-a[i]] > 0)
{
a[-a[i]] = -a[-a[i]];
}
else
{
return -a[i];
}
}
}
//	return 0;
}

int main(int argc, char *argv[])
{
int a[]={4,1,2,1,3};
int length = sizeof(a)/sizeof(int);

cout << "Duplication is : " << xor_findDup(a,length) << endl;
return 0;
}


2.循环链表法

/*
找出数组{1,2,3,4,...N-1}中出现的唯一重复数

*/

#include <iostream>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int xor_findDup(int* a,int count)
{
int i = 0;
int x = 0,y = 0;
do
{
x = a[a[x]]; //一次走两步
y = a[y];	 //一次走一步
cout << x << "->" << a[x] << "->"<<a[a[x]] << " ; " << y << "-" << a[y] << endl;
}while(x != y);  //找到环中的一个点
cout << endl;
cout << x << endl;
do
{
x = a[x];   //一次走一步
y = a[y];	 //一次走一步
cout << x << "->" << a[x] << " ; " << y << "->" << a[y] << endl;
} while(x != y);  //找到入口点
return x;
//	return 0;
}

int main(int argc, char *argv[])
{
int a[]={4,1,2,3,4};
int length = sizeof(a)/sizeof(int);

cout << "Duplication is : " << xor_findDup(a,length) << endl;
return 0;
}


不能从元素0开始,防止死循环!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: