您的位置:首页 > 其它

《leetCode》:Single Number

2016-03-01 10:13 295 查看

题目

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?


思路

此题在《剑指Offer》中出现过。

根据 本身异或其本身的结果为0,0异或任意数A都等于A,根据题意在数组中只有一个数出现了一次,因此,将数组中的所有数进行异或即可求解

实现代码如下:

int singleNumber(int* nums, int numsSize) {
if(nums==NULL||numsSize<1){
return 0;
}
int xorValue=nums[0];
for(int i=1;i<numsSize;i++){
xorValue^=nums[i];
}
return xorValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: