python 如何找出数组中出现一次的数
在python程序员面试算法宝典,第四章145页的一题,如下描述:
一个数组里,有三个数只出现了一次,其余数的出现次数都是偶数,找出这三个只出现一次的数中的任意一个。
原文代码如下:
def find_odd(list):
if not list:
return None
i=0
while i<32:
j=0
res1=res0=count1=count0=0
while j<len(list):
if ((1<<i)&list[j])==1:
count1+=1
res1^=list[j]
else:
count0+=1
res0^=list[j]
j+=1
#只有res1!=0才能确定该位可以区分开三个唯一出现的数
#只有count为奇数的那一组才能通过异或运算解出其中的一个数
if count1%2==1 and res0!=0:
return res1
if count0%2==1 and res1!=0:
return res0
i+=1
return None
list=[1,3,5,7,1]
res=find_odd(list)
print(res)
运行截图如下:
这里出了什么问题,自己推导感觉没错,希望大佬指点。