Total Accepted: 114785
Total Submissions: 235971
Difficulty: Medium
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?
这个题目 ,要找出来也很简单 ,但有个更牛鼻的方法就是利用异或 ,先看代码 ;
int singleNumber(int* nums, int numsSize) {
int i ,des=0 ;
for ( i = 0 ; i < numsSize ; i++ )
des = des ^ *(nums+i) ;
return des ;
}
异或就是在二进制编码上不同就为1 ,相同就为 0 。
如 111 ^ 110 = 001 ;
所以 7^6 = 1 ;
任何数异或0 ,结果都是原来的数 。因为0并不会改变里面的1 ;
相同的数异或得到的答案就是0. 如 111 ^ 111 = 000 ;
利用这个知识就能轻松的解决这个问题了 。