首页 > 代码库 > [ LeetCode] Single Number
[ 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?
原题链接
解题思路
数组含有n个数,其中有一个数只出现1次,其余的数都出现两次,求只出现一次的数。
这个主要考察的是位运算中的异或运算的性质-----当两个相等的数做异或运算他们的值为0(a^a = 0)。本题中对数组中所有的数做异或,那么最后异或的结果就是只出现1次的数。思想很简单代码如下。
代码实现:
class Solution { public: int singleNumber(int A[], int n) { if(A==NULL || n<=0) return 0; int ret = A[0]; for(int i=1; i<n; ++i) ret ^= A[i]; return ret; } };
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28388241 )
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。