HDU 2095:find your present (2) 两种思路

HDU 2095:find your present (2)

HDU2095链接

找最优解直接看思路2
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

HintHint
use scanf to avoid Time Limit Exceeded

基本题意:多样例输入,输入数字n,n一定为奇数(当n为0时停止输入),下一行紧接着有n个数字,找出其中只出现过一次的数字并输出。题目保证了除了答案数字外,其他的数都是偶数个。

思路1:第一种方法比较简单理解,也是我首次写想到的方法,就是直接排序。因为在排序过以后,不是答案的数字的左边或右边(如果左右数字存在)一定能找到相等的数字,而答案数字是一定找不到的,所以当找到这种数字时,就一定是答案。
思路1代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
    int N;
    while(cin>>N&&N)
    {
        int a[N];
        for(int i=0;i<N;++i)
            scanf("%d",&a[i]);
        sort(a,a+N);//排序
        for(int i=0;i<N;++i)
        {
            if(i-1>=0)
            {
                if(a[i]==a[i-1])
                    continue;
            }
            if(i+1<N)
            {
                if(a[i]==a[i+1])
                    continue;
            }
            cout<<a[i]<<endl;
        }
    }
}

思路2:这是我在评论区看到的普遍方法,也是相比于思路1运行更快的方法,更是代码量很少的一种方法:异或。一个数字,只要与一个数字异或过偶数次,那么它一定会变回自己,亲测有效。而一个数字与0进行异或一定还是自己。所以利用这两个想法,只要让一个变量初始化为0,然后与所有输入的数字进行异或,然后这个变量一定会异或到答案,然而答案与其他数字进行偶数次异或之后还是答案本身,所以异或完所有的输入以后,这个变量最终结果就是答案。
思路2代码(想到写起来就太快了):

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    int n;
    while(cin>>n&&n)
    {
        int a,ans=0;
        for(int i=0;i<n;++i)
        {
            scanf("%d",&a);
            ans^=a;
        }
        cout<<ans<<endl;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值