问题描写叙述:
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; }};