数组中只出现一次的数字
时间限制:1秒 空间限制:32768K 热度指数:206605
本题知识点: 数组
算法知识视频讲解
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
法1.内置函数
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
# 法1. 内置函数
ans = []
for i in array:
if array.count(i) == 1:
ans.append(i)
return ans
法2.数组
这里利用了题目的两个条件:
1.重复的只出现两次,所以如果数字出现两次的话,先append,再remove
2.只有两个数字只出现一次,如果找前两个出现一次的数字的话,最后不能直接返回tmp
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
# 法2.数组
tmp = []
for a in array:
if a in tmp:
tmp.remove(a)
else:
tmp.append(a)
return tmp
update:2019年10月7日
字典法(更普适)
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
# 1.维护一个字典:key是每一个数字,value是出现的次数
res = {}
# 2.维护一个大于两次出现的数字的列表,如果该数字出现多于两次,则放在这里边
temp = []
for i in array:
if i not in temp:
res[i] = res.get(i, 0) + 1
if res[i] > 1:
del res[i]
temp.append(i)
return list(res.keys())