給定一個數組,其中只有一個數出現一次,別的數都出現3次,找出這個數(go)
阿新 • • 發佈:2018-11-05
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 }