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?
题目给的条件限定很多,其中其他的每一个元素都肯定出现两次这个很关键。
利用异或操作的特性:
1. A xor 0 = A
2. 可交换属性, a xor ( b xor c) = ( a xor b ) xor c
设置起始返回值为0, 对数组中所有的元素做异或操作,最后剩下来的就是结果。
public int singleNumber(int[] A) { int result = 0; for (int i = 0; i < A.length; i++) { result = result ^ A[i]; } return result; }