您的位置:首页 > 其它

leetcode#136 Single Number

2015-06-04 13:02 330 查看

github链接

本题leetcode链接

题目描述

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?

Tag: hashTable Bit manipulation

题目分析

有一个数组,里面除以一个只出现一次的元素外,其他所有元素都出现了两次。要求找出这个元素。要求时间复杂度为O(n)。最好不要使用额外的空间。

题目提示了使用位操作。

异或操作满足下面的性质:

交换律

结合律

0和任何数异或等于任何数本身

两个相等的数异或等于0

举个例子模拟一下

假设数组为
2 6 8 9 4 3 4 2 6 8 9
,我们要找的元素是3

把所有元素异或得到
2^6^8^9^4^3^4^2^6^8^9


应用交换律和结合律,得到
(2^2)^(6^6)^(8^8)^(9^9)^(4^4)^3


应用性质3,得到
0^0^0^0^0^3


应用性质4,得到3

把所有元素异或起来,因为相同的数异或结果为0,最后的结果肯定就是没有相同元素和它异或的那个元素,也就是我们要找的只出现一次的元素。

代码实现(JAVA)

int singleNumber(int A[], int n) {
int i = 0;
int result = 0;
for(i=0;i<n;i++)
result = result^A[i];
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 位操作 算法