一个整型数组里除了两个数字只出现一次,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
数据范围:数组长度
,数组中每个数的大小 
要求:空间复杂度
,时间复杂度 )
要求:空间复杂度
提示:输出时按非降序排列。
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param array int整型一维数组 # @return int整型一维数组 # class Solution: def FindNumsAppearOnce(self , numbers: List[int]) -> List[int]: # write code here d=dict() for num in numbers: if not d.get(num): #target-numbers[i-1],则放入哈希表中 d[num]=1 else: d[num]+=1 d1=sorted(d.items(), key=lambda x:x[1]) return sorted([d1[0][0],d1[1][0]])
class Solution: def FindNumsAppearOnce(self , array: List[int]) -> List[int]: # write code here if len(array) < 2: return [] diff = 0 for num in array: diff ^= num diff &= -1 * diff num1, num2 = 0, 0 for num in array: if num & diff == 0: num1 ^= num else: num2 ^= num return [num1, num2] if num1 < num2 else [num2, num1]
class Solution:
# 异或运算:相同数字为0,相异数字为1
# 空间复杂度:O(1) 时间复杂度:O(n)
def FindNumsAppearOnce(self , array: List[int]) -> List[int]:
res = [0, 0]
temp = 0
for i in range(len(array)):
temp ^= array[i] # 0 ^ 数 = 数
k = 1
# 找到两个数不相同的第一位
while k & temp == 0:
k <<= 1 # 左移,右边补零
for i in range(len(array)):
# 遍历数组,对每个数分类
if k & array[i] == 0:
res[0] ^= array[i]
else:
res[1] ^= array[i]
res.sort()
return resclass Solution:
# 哈希表
# 空间复杂度:O(n) 时间复杂度:O(n)
def FindNumsAppearOnce(self , array: List[int]) -> List[int]:
mp = {}
res = []
for i in array:
if i in mp:
mp[i] += 1
else:
mp[i] = 1
for i in mp:
if mp[i] == 1:
res.append(i)
res.sort()
return res
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param array int整型一维数组 # @return int整型一维数组 # class Solution: def FindNumsAppearOnce(self , array: List[int]) -> List[int]: # write code here from collections import Counter dic = Counter(array, reverse=False) res = [] for k, v in dic.items(): if v == 1: res.append(k) if sorted(res) != res: return sorted(res) ## 用于指定顺序的情况 return res