[LeetCode] Single Number

来源:互联网 发布:淘宝客服快捷短语设置 编辑:程序博客网 时间:2024/06/06 09:42

Title:

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?


题解:

对所有的元素用异或操作,如果两个元素是相同的,那么总有一次,他们会变为0,这样成对成对的消失(像玩连连看),最后就剩下唯一的元素。估计是我的算法资历较浅的缘故,初看到这个方法,觉得太精妙,很有启发。


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


0 0