Problem Description
In the new year party, everybody will get a "special present".Now it's your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and your present's card number will be the one that different from all the others, and you can assume that
only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card number of 3, because 3 is the number that different from all the others.
|
Input
The input file will consist of several cases.
Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input. |
Output
For each case, output an integer in a line, which is the card number of your present. |
Sample Input
5 1 1 3 2 2 3 1 2 1 0 |
Sample Output
3 2 |
先给个Time Limit Exceeded的Answer:
#include <stdio.h>
#include <string.h>
int array[1000000];
int count[1000000];//记录对应数组元素出现了几次
int main()
{
int n;
while (scanf("%d", &n), n) { //或:(~scanf("%d", &n) && n)
memset(array, 0, sizeof(array));
memset(count, 0, sizeof(array));//必须是sizeof(array),因为memset()第三个参数是接收要设置几个字节的大小
for (int i=0; i<n; ++i) {
scanf("%d", &array[i]);
}
for (int i=0; i<n-1; ++i) {
for (int j=i+1; j<n; ++j) {
if (array[i]==array[j] && count[j]==0) {
count[i]++;
count[j]++;
}
}
}
for (int i=0; i<n; ++i) {
if (count[i] == 0) {
printf("%d\n",array[i]);
}
}
}
return 0;
}
于是,就有了下面这个改进版本:
//对输入的数据排序后,满足区间(array[i-1],array[i+1])的array[i]就是所要找的唯一解
#include <stdio.h>
#include <string.h>//memset()
#include <algorithm>
int array[1000000];
int main()
{
int n;
while (scanf("%d", &n), n) {
memset(array, 0, sizeof(array));
for (int i=0; i<n; ++i) {
scanf("%d", &array[i]);
}
std::sort(array, array+n);
if (n == 1) {
printf("%d\n", array[0]);
continue;
}
if (array[0] < array[1]) {
printf("%d\n", array[0]);
continue;
}
if (array[n-2] < array[n-1]) {
printf("%d\n", array[n-1]);
continue;
}
for (int i=1; i<n-1; ++i) {
if (array[i-1]<array[i] && array[i]<array[i+1]) {
printf("%d\n", array[i]);
}
}
}
return 0;
}
虽然上面的答案可以AC,但是上面的方法没有使用到题目中给的条件:“only one number appear odd times”,所以此答案自然不是最优解,也不是出题人想要的答案!
经过一番思考未果,最终本人上网搜寻到了下面这个巧妙的答案:
//利用到了异或的性质:1、一个数异或自己为0; 2、任何数与0异或都是其本身
#include <stdio.h>
int main()
{
int n;
while (scanf("%d", &n), n) {
int x, ans = 0;//任何数与0异或都是其本身
for (int i=0; i<n; ++i) {
scanf("%d", &x);
ans = ans^x;
}
printf("%d\n", ans);
}
return 0;
}
补充一点:
memset函数是以字节为单位进行赋值的,而一个整型int是4字节(由printf("%d",sizeof(int));可知),所以不能用memset给int整型数组进行赋值初始化,而只能对其清零!