Force link :https://leetcode-cn.com/probl...
Their thinking :
- Conventional thinking : Use hash / Set to make de duplication judgment , But space needs to be reopened , Resulting in increased spatial complexity
- Exclusive or : English is exclusive OR, Abbreviation xor, It has the following algorithm :
As shown above , In the title , Only one number appears only once , According to the law of Union & Commutative law & Reflexive law , Two identical numbers Exclusive or The result is 0,0 With any number Exclusive or Equal to the number itself , So all numbers and initialization numbers 0 Or , The last value is the number that appears once
func singleNumber(nums []int) int {
single := 0
for _, v := range nums {
single ^= v
}
return single
}