一个整型数组里除了一个数字之外,其他的数字都出现了两次。要求时间复杂度是O(n),空间复杂度是O(1),如何找出数组中只出现一次的数字

思路分析:任何一个数字异或它自己都等于0,根据这一特性,如果从头到尾依次异或数组中的每一个数字,因为那些出现两次的数字全部在异或中抵消掉了,所以最终的结果刚好是那些只出现一次的数字。

代码如下:

#include "stdafx.h"
#include <stdio.h>
int findNotDouble(int a[], int n)
{
    int result = a[0];
    int i;
    for (i = 1; i < n; ++i)
        result ^= a[i];
    return result;
}
int main()
{
    int array[] = { 1, 2, 3, 2, 4, 3, 5, 4, 1 };
    int len = sizeof(array) / sizeof(array[0]);
    int num = findNotDouble(array, len);
    printf("%d\n", num);
    getchar();
    return 0;
}

    效果如图:

posted @ 2014-03-14 10:18  源子陌  Views(806)  Comments(0Edit  收藏  举报