您的位置:首页 > 其它

Leetcode: Single Number

2013-10-05 22:57 309 查看
最近做Leetcode上的题目,感觉有些挺有趣的,比如这个Single Number题目:

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?

如果没有时间和空间复杂度的限制,这道题并没有什么难处,大可以扫一遍数组,然后用hashmap记录每个数值出现的次数。不过hsahmap需要额外的空间,在这里并不合适。如果不用hashmap,还要保持线性时间复杂度,解决问题的思想应该也是hash。不过这里怎么hash就有一些trick了。int是按二进制存储的,从int到二进制表示就是一种hash。此外,由于不能用额外的存储空间,我们必须想其他的方法来区别出“出现一次”和“出现二次”。这里二进制的异或运算就显示了它强大的地方。两个相同的数异或值是0,这给了我们很大的启示,如果把数组里所有的数异或起来,那么最后剩下的就只有出现一次的数,bingo! 代码如下:

class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int result=0;
for(int i=0;i<n;i++){
result^=A[i];
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: