题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。例如:{2,4,3,6,3,2,5,5},因为只有4,6这两个数字只出现了一次,其他数字都出现了两次,所以输出4和6.
思路1
暴力法:
- 创建一个字典
- 数组按键值和出现次数保存到字典里
- 返回只出现一次的两个数
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.dict={}
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
if not array:
return None
res=[]
for i in array:
if i not in self.dict:
self.dict[i]=1
else:
self.dict[i]+=1
for i in self.dict:
if self.dict[i]==1:
res.append(i)
return res
思路2
这个数组里只有出现一次和两次的数,很奇怪。可以想到相同的数彼此异或可以消除。剩下的两个只出现一次的数是消除不了的。
- 遍历数组,先得到数组彼此间的一个异或结果
- 根据结果最右边1的位置,将两个只出现一次的数字分开,即分成了两组数
- 再按之前的方法,将两组数分别异或,分别得出的两个数即为结果
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
if not array:
return None
x=0
for i in array:
x^=i
count=0
while x&1!=1:
count+=1
x>>=1
one=[]
two=[]
for i in array:
if (i>>count)&1!=1:
one.append(i)
else:
two.append(i)
x1=0
x2=0
for i in one:
x1^=i
for i in two:
x2^=i
return x1,x2
测试用例
if __name__=='__main__':
s=Solution()
numbers=[2,4,3,6,3,2,5,5]
print(s.FindNumsAppearOnce(numbers))
http://blog.sina.com.cn/s/blog_13c6397540102x0c3.html 这位同学讲的很好