code第一部分数组:第二十二题 偶数次中查找单独出现一次的数

code第一部分数组:第二十二题 偶数次中查找单独出现一次的数

Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using
extra memory?

分析:采用异或的方法查找;

#include <iostream>
using namespace std;

int singleNumber(int A[], int n)
{
    int x = A[0];
    for (int i = 1; i < n; ++i)
    {
        x ^= A[i];
    }

    return x;
}


int main()
{
    int a[7]={1,3,4,4,3,2,1};
    int ans=singleNumber(a,7);

    cout<<"the ans is "<<ans;
    return 0;
}
这种方法不仅能解决两次中单独一次的情况,偶数次中单独出现一次的情况也能找出来。
 
如果能使用额外空间,也可以使用hash表来做。
原文地址:https://www.cnblogs.com/tao-alex/p/6443065.html