single number
Given an array of integers, every element appears twice except for one. Find that single one.
就是只有一个数不同,其他都是两两相同,找出来这个数
Note:
Your algorithm should have alinear runtime
complexity. Could you implement itwithout using extra memory
?
思路
本来想着排序的,但是那样怎么样也不是线性时间
然后想到相加和不同,但是这个方向是对的,但是理论上怎么也行不通所以最后发现是用位运算,
异或
代码
int singleNumber(int* nums, int numsSize) {
int single = 0;
int i ;
for(i=0; i< numsSize;i++)
{
single= single^nums[i];
}
return single;
}