Any number is XORed, and the result is still the original number, that is, a⊕0=a.
Any number is XORed with itself, and the result is 0, that is, a⊕a=0.
XOR operation satisfies commutative law and associative law, that is, a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b.
136. Numbers that occur only once
Given a non-empty array of integers, each element appears twice except for a certain element that appears only once. Find the element that appears only once.
Explanation:
Your algorithm should have linear time complexity. Can you do it without using extra space?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
class Solution {
public int singleNumber(int[] nums) {
int single = 0;
for (int num : nums) {
// 把所有的数组的所有元素异或起来,两两相同的都异或为0,
// 那么结果只剩下孤单的那一个元素
single ^= num;
}
return single;
}
}
simplify:
class Solution {
// 简化
public int singleNumber(int[] nums) {
for (int i = 1; i < nums.length; i++) {
nums[0] ^= nums[i];
}
return nums[0];
}
}