题目描述:
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
解法1:
通过遍历把统计的数字次数存入python内置的字典dict,然后再搜寻出现一次的数字
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
tagdict={}
for i in array:
if i in tagdict:
tagdict[i]+=1
else:
tagdict[i]=1
taglist=[]
for j in tagdict:
if tagdict[j]==1:
taglist.append(j)
return taglist
解法2:
通过使用python的count计数函数
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
taglist=[]
for i in array:
if array.count(i)==1 and i not in taglist:
taglist.append(i)
return taglist
两种方法在牛客网提交的测评结果对比
法1:运行时间:24 ms 占用内存:5624K
法2:运行时间:32 ms 占用内存:5628K