1.思路
用两个数one=0、two=0分别记录bits位上1出现的次数,如果一个数出现一次,则one等于这个数,two=0; 如果一个数出现两次,则two等于这个数, one等于0;如果一个数出现第三次,则one = 0, two = 0 ,three等于这个数。
我们以数组{2, 1, 2, 2}为例:
初始: one = 0, two = 0 three
a. 数字2加入其中,则 one = 10(对应的10进制为2),two = 0
b. 数字1加入其中,则one = 11(对应的10进制为3),two = 0, two等于0表明前面两个数字没有重复的位
c. 数字2加入其中, 则one = 1(对应的10进制为1), two = 10(对应的10进制为2), two等于2表明前面三个数字有重复的位
d.数字2加入其中,则one = 11 (对应的10进制为3), two = 10(对应的10进制为2), three = one & two = 10(十进制为2),表明有数字位重复出现3次,one = one & (^three), two = two &(^three),去掉one和two中与three相同的位,即去掉了出现3次的数字
算法: one = 0 two = 0 three
two |= one & t
one ^= t
three = one & two
one &= (^three) 如果用python,则该处对应的是 one &= (~three)
two &= (^three) 如果用python,则该处对应的是 two &= (~three)
代码如下:
func singleNumber(nums []int) int {
var one = 0
var two = 0
var three int
for i:= 0; i < len(nums); i++ {
temp := nums[i]
two |= one & temp
one ^= temp
three = one & two
one &= ^three
two &= ^three
}
return one
}