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.
0和一个数异或,则为该数。
由于数组中,每个数,都会出现两遍。只有一个数例外。
则对该数组元素全体作完异或后,结果为那个例外的数。 因为其他数都互相抵消了。
class Solution { public: int singleNumber(vector<int>& nums) { int ans = 0; for (int i=0; i<nums.size(); i++) { ans ^= nums[i]; } return ans; } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/46237339