问题描述:
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?
解题思路:本题可以用位运算来求解。因为a^0=a,a^a=0,a^b=b^a(即异或运算满足交换律),且已知数组中除了要找的元素,每个元素都出现两次。则可以将数组中的各元素依次异或。根据异或运算的交换律,可以改变运算顺序使出现两次的元素相邻,则所有出现两次元素异或的结果为0。最后得到异或的结果为要找的元素。
代码:
class Solution { public: int singleNumber(int A[], int n) { int i; int result = A[0]; for(i = 1;i < n;i++) result = result ^ A[i]; return result; } };
原文地址:http://blog.csdn.net/yao_wust/article/details/40424119