題目描述
一個整型數組里除了兩個數字之外,其他的數字都出現了偶數次。請寫程序找出這兩個只出現一次的數字。
樣例
返回[a,b]
想法一:
通常想法,使用HashMap,兩邊遍歷。
class Solution:
# 返回[a,b] 其中ab是出現一次的兩個數字
def FindNumsAppearOnce(self, array):
# write code here
dict = {}
list = []
Counter
for i in array:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
for key, value in dict.items():
if value == 1:
list.append(key)
return list
想法二:
思路與一相同,但是想使用python的函數式編程,但是自己想了半天也沒有做出來,之后看了討論區,發現有Counter數據結構,對於這個問題就很簡單了。
class Solution:
# 返回[a,b] 其中ab是出現一次的兩個數字
def FindNumsAppearOnce(self, array):
# write code here
return list(map(lambda x: x[0], Counter(array).most_common()[-2:]))
想法三:
使用位運算,兩個相同的數異或之后為0,所以遍歷數組,兩兩異或之后必定會且至少有一位為1,那么就找到那個1的位置,說明在這一位上這兩個數是不相同的,那么再遍歷一遍,每個數都移位,判斷該位置是否為1,如果是1就與一個數異或,如果不是就與另一個數異或,最后便會得到兩個唯一的數
class Solution:
def FindNumsAppearOnce(self, array):
if not array:
return []
# 對array中的數字進行異或運算
sum = 0
for i in array:
sum ^= i
index = 0
while (sum & 1) == 0:
sum >>= 1
index += 1
a = b = 0
for i in array:
if self.fun(i, index):
a ^= i
else:
b ^= i
return [a, b]
def fun(self, num, index):
num = num >> index
return num & 1
最后
刷過的LeetCode或劍指offer源碼放在Github上了,希望喜歡或者覺得有用的朋友點個star或者follow。
有任何問題可以在下面評論或者通過私信或聯系方式找我。
聯系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063