1-N放在N+1个元素的数组中,只有唯一的一个元素值重复,其他均只出现一次。每个数组元素只能访问一次,设计一个算法,将它找出来,不用辅助存储空间。这个问题其实就是编程之美上面机器故障的题的翻版,解法就是利用异或操作求解代码不难写:
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#include <cassert>
using namespace std;
const int size = 1001;
int array[size];
void generateArray(int repeatNum)
{
assert(repeatNum > 0 && repeatNum <= 1000) ;
int i;
for(i = 1; i < size; i++)
array[i - 1] = i;
array[i - 1] = repeatNum;
}
int getRepeatNum(int (&array)[size])
{
int result = 0;
int temp = 0;
for(int i = 0; i < size - 1; i++)
result ^= i + 1;
for(int i = 0; i < size; i++)
temp ^= array[i];
return (result ^ temp);
}
void main()
{
int number;
cout << "enter the repeat number:" << endl;
cin >> number;
generateArray(number);
int result = getRepeatNum(array);
cout << "the repeat number is: " << result << endl;
}
结果如下:
下面同样是由异或求出机器故障的解:
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#include <cassert>
using namespace std;
const int size = 9;
int array[size] = {1, 2, 3, 3, 5, 4, 4, 1, 5};
int getResult(int (&array)[size])
{
int result = 0;
for(int i = 0; i < size; i++)
result ^= array[i];
return result;
}
void main()
{
int result = getResult(array);
cout << "the obstacle mechine: " << result << endl;
}
结果: