D

来源:互联网 发布:欧美品牌男装淘宝 编辑:程序博客网 时间:2024/04/30 13:40

D - find your present (2)

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

  >use scanf to avoid Time Limit Exceeded

代码块

#include<iostream>#include<algorithm>#include<string.h>#include<stdlib.h>using namespace std;int a[1000001];int main(){    int n,i,j;    int flag=0;    while(cin>>n)    {        for(i=0;i<n;i++)          scanf("%d",&a[i]);        sort(a,a+n);        j=1;        for(i=0;i<n;i=i+2)//两两进行查询,如果两数相等,执行j++,i继续往后加2       {         if(a[i]==a[i+1])           j++;         else         //当执行到两数不相等时,就输出前面那一个数,由于输入的数字是偶数,而i每一次是加2,         //所以执行到最后,就只有一个数,那么就把最后那一个数字输出。         {            printf("%d\n",a[i]);            break;        }       }    }}

(2)使用位异或来做,
位异或的运算法则:
1、a^b = b^a。
2、(a^b)^c = a^(b^c)。
3、a^b^a = b。
对于一个任意一个数n,它有几个特殊的性质:
1、0^n = n。
2、n^n = 0。
所以可以通过每次异或运算,最后剩下的值就是出现奇数次的那个数字。

通过位运算的这些性质,可以通过不借用中间变量实现a,b的值的交换。

#include<stdio.h>#include<iostream>#include<algorithm>#include<string.h>#include<stdlib.h>using namespace std;int main(){   int i,k,n,s;   while(scanf("%d",&n),n)   {       s=0;    for(i=0;i<n;i++)    {      scanf("%d",&k);        s^=k;    }   printf("%d\n",s);   }}

脚注

当输入5时
5
1 1 2 2 3
最后输出的数字应该是3,前面的数字都是两两一样数字,所以当比较到最后一个数字的时候,就把数字3输出。
5
1 1 2 3 3
前面的数字是两两一样的,当比较到2 3时就不一样了,这时就输出2;

原创粉丝点击