Single Number
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?
分析:
整理异或的知识:
1、实现两个值的交换,而不必使用临时变量。
例如交换两个整数a=10100001,b=00000110的值,可通过下列语句实现:
a = a^b; //a=10100111
b = b^a; //b=10100001
a = a^b; //a=00000110
2、异或的性质
(1)交换律
(2)结合律(即(a^b)^c == a^(b^c))
(3)对于任何数x,都有x^x=0,x^0=x
(4)自反性 A XOR B XOR B = A xor 0 = A
3、本题的分析
(1)本题主要是运用了异或的交换律和结合律;我们考虑将所有的数进行异或,根据交换律,把所有出现两次的数交换到一起;然后根据结合律,两两结合,B XOR B = 0;最后就只剩下出现一次的数和0异或,根据自反性 A XOR B XOR B = A xor 0 = A。
(2)异或,不仅能处理两次的情况,只要出现偶数次,都可以清零。
(3)为了不用额外的空间,则将第一个位置作为结果输出。
//方法一:异或,循环。时间复杂度 O(n) ,空间复杂度 O(1) class Solution { public: int singleNumber(vector<int>& nums) { for(int i = 1; i < nums.size(); i++) nums[0] = nums[0] ^ nums[i] ; return nums[0]; } };
//方法二:异或,STL。时间复杂度 O(n) ,空间复杂度 O(1) class Solution { public: int singleNumber(vector<int>& nums) { return accumulate(nums.begin(), nums.end(), 0, bit_xor<int>()); } };
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46605829