136. Single Number
题目
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
算法
巧妙利用位运算,异或运算符“^”,相同为0,不同为1。
时间复杂度为O(n),且空间复杂度为O(1)
这里有相关运算符的解释还比较全面,感谢该作者的博文:C语言的二进制 十进制 ^&|~ >>
代码
int singleNumber(int* nums, int numsSize) {
int i;
int a = 0;
for(i = 0;i<numsSize;i++){
a^=nums[i];//异或运算,相同为0,不同为1
}
return a;
}