136. Numbers that appear only once
The main knowledge points examined in this question arebit operations (here is XOR)
If the space complexity is not required, the space complexity is O(1) , there are many ways. But there is such a requirement here.
can be achieved by bit operation .
The XOR operation ⊕ has the following three properties:
-
If any number is XORed with 0, the result will still be the original number, that is, a⊕0=a.
-
If any number is XORed with itself, the result is 0, that is, a⊕a=0.
-
The XOR operation satisfies the commutative law and associative law, that is, a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b.
-
XOR with 0 as itself.
-
XOR with itself is 0
-
Satisfy the commutative law and associative law
Consider this question
So in this question, there are a total of 2n+1 numbers, n numbers appear twice, and 1 number appears once. So XOR ⊕ all these 2n+1 numbers, the final result is the number that only appears once.
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int num:nums){
res ^= num;
}
return res;
}
}