Leetcode 位运算 Single Number
时间:2014-05-11 02:37:42
收藏:0
阅读:397
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Single Number
Total Accepted: 20063 Total Submissions: 44658Given 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?
题意:在一组数组中除一个元素外其它元素都出现两次,找出这个元素
思路:位运算。异或。因为异或操作可以交换元素的顺序,所以元素异或的顺序没影响,最后出现再次的元素都会被异或掉,相当于0和只出现一次的那个元素异或,结果还是那个元素
推广:这个方法也适合于出现其它元素都出现偶数次,而要找的元素出现奇数次的情况
复杂度:时间O(n),空间O(1)
相关题目:Single Number IIclass Solution { public: int singleNumber(int A[], int n) { int temp = 0; for(int i = 0; i < n; i++){ temp = temp ^ A[i]; } return temp; } };
评论(0)