您的位置:首页 > 编程语言 > C语言/C++

136 Single Number

2016-09-08 20:21 225 查看
问题描述:

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?

问题说明:题目要求时间复杂度O(n),不使用额外内存。只能再次借助位操作的特性。因为a^a=0,0^a = a.

也就是说,相同的两个数做异或可以抵消掉,0对任何数做异或不影响这个数。所以将所以的数在一起做一遍异或就可以了。

PS:对于异或的特性还需要多多了解,这方便欠缺很多

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