题目链接:
题目:
Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
题目分析:
给定一个数字数组,里面所有的元素都出现两次,仅有一个元素出现一次,找出出现一次的数。要求:线性的时间复杂度和不要额外的内存开销。
解题思路:
既然要用到线性复杂度,那就只能扫一遍数组。
主要利用XOR的性质,XOR本来是位运算符,即0与0、1与1异或为0,1与0、0与1异或为1,而在十进制中:相同的数异或为0,0和任意数异或还是其本身。而且a^b^a^b^c = a^a^b^b^c = c,满足交换律。
所以我们只要将数组里的所有数都异或。
注意初始值弄成0,因为0和任意数异或还是其本身。
AC代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len = nums.size();
int res = 0;
for(int i = 0;i < len;i++)
{
res ^= nums[i];
}
return res;
}
};