#include <set>
#include <iostream>
#include <iterator>
using namespace std;
/*
* 从100W个数中最快找出两个相同的数
*/
// 从set容器中查找
void method1()
{
// windows下栈空间只有2M,所以得在heap下
int * arr = new int[1000000];
for( int i = 0; i < 1000000; ++i ) {
arr[i] = i + 1;
}
arr[95342] = 100;
cout << "start insert" << endl;
set<int> si;
int i;
for( i = 0; i < 1000000; ++i ) {
pair< set<int>::iterator, bool > pi = si.insert( arr[i] );
if( !pi.second ) // 插入失败,这里就是这样的
break;
}
cout << "end insert" << endl;
int j;
for( j = 0; j < i; ++j ) {
if( arr[i] == arr[j] )
break;
}
cout << "index: " << j << " value: " << arr[j] << endl;
cout << "index: " << i << " value: " << arr[i] << endl;
delete [] arr;
}
/*
* 从100W个数中最快找出两个不同的数
*/
// 编程之美算法:异或算法
void findIsolateTwo( int * arr, int len, int * result )
{
int i, all = 0, flag = 1;
for( i = 0; i < len; ++i ) // 异或所有数
all ^= arr[i];
while( !( all & flag ) ) // 寻找过滤位,即为非0的位
flag <<= 1;
result[0] = result[1] = 0;
for( i = 0; i < len; ++i ) { // 利用过滤位区分
if( flag & arr[i] )
result[0] ^= arr[i];
else
result[1] ^= arr[i];
}
}
void method2()
{
// windows下栈空间只有2M,所以得在heap下
int * arr = new int[1000000];
for( int i = 0; i < 1000000; ++i ) {
arr[i] = 1000;
}
arr[95342] = 22666666;
arr[52481] = 41257625;
int result[2] = {};
// 不行,和预想不一样
findIsolateTwo( arr, 1000000, result );
cout << "value: " << result[0] << endl;
cout << "value: " << result[1] << endl;
delete [] arr;
}
int main(int argc, char *argv[])
{
method1();
method2();
return 0;
}