Recently, the epidemic situation brushed water at home. This problem is to find the number
that appears only once in the array. The time complexity is O (n), and no new space is stored.
Title: The number
that appears only once has been done once on the Jianzhi Offer, it is sorted, and then whoever has only one number is clear at a glance.
But the time complexity is O (logN + N).
The idea this time is to use XOR operation. The important concepts of XOR operation are as follows (where N is any number):
- 0 xor N = N
- N xor N = 0
- The XOR operation satisfies the exchange law and the combination law
, namely: a xor b xor a = (a xor a) xor b = 0 xor b = b
So when you see this, you suddenly feel ashamed and record ashamed ...
class Solution {
public int singleNumber(int[] nums) {
int xor = 0;
for(int i: nums){
xor ^= i;
}
return xor;
}
}