Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
数组中,只有一个数出现一次,其余数均出现两次。求出现一次的那个值。
异或的三个性质:
// 异或满足交换律,a1 ^ a2 ^ .... ^ an ^ a1 ^ .... ^ an-1 = (a1^a1)^(a2 ^a2) ^(....) ^(an-1 ^ an-1) ^ an
// a ^ a = 0;
// a ^ 0 = a;
显然将所有数字异或后,得到的结果即为出现一次的值。
//java
class Solution {
public static int singleNumber(int[] nums) {
int i=0;
int result=0;
while(i<nums.length){
//数组中元素不断的做异或运算
result=result^nums[i];
i++;
}
return result;
}
}