当前位置:网站首页>Leetcode topic [array] -136- numbers that appear only once

Leetcode topic [array] -136- numbers that appear only once

2022-07-04 08:30:00 LabRat

Force link :https://leetcode-cn.com/probl...
Their thinking :

  1. Conventional thinking : Use hash / Set to make de duplication judgment , But space needs to be reopened , Resulting in increased spatial complexity
  2. Exclusive or : English is exclusive OR, Abbreviation xor, It has the following algorithm :
    image.png
    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
}
原网站

版权声明
本文为[LabRat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141452321524.html