题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
解题思路
思路1:
用Python中的字典(键–值对)。以数组中的数字为键,以其出现的次数为值。最后找到值为1对应的键。时间复杂度O(2n), 空间复杂度O(2n)。
def FindNumsAppearOnce(self, array):
if len(array) < 2:
return None
dict, res = {}, []
for num in array:
dict[num] = 1 if num in dict else 0
for key in dict:
if dict[key] == 0:
res.append(key)
return res
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
思路2:来自这里
用异或求解。异或运算的性质:任何一个数字异或它自己都等于0 。
如果数组中只有一个数字出现过一次,其余数字都出现了两次;这样的话如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现一次的数字,因为那些出现两次的数字全部在异或中抵消掉了。如果能够把原数组分为两个子数组,在每个子数组中,包含一个只出现一次的数字,而其它数字都出现两次。在两个子数组中分别求出这两个只出现一次的数字。
还是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其它数字都出现了两次,在异或中全部抵消掉了。由于这两个数字肯定不一样,那么这个异或结果肯定不为0 ,也就是说在这个结果数字的二进制表示中至少就有一位为1 。我们在结果数字中找到第一个为1 的位的位置,记为第N 位。现在我们以第N 位是不是1 为标准把原数组中的数字分成两个子数组,第一个子数组中每个数字的第N 位都为1 ,而第二个子数组的每个数字的第N 位都为0 。现在我们已经把原数组分成了两个子数组,每个子数组都包含一个只出现一次的数字,而其它数字都出现了两次。因此到此为止,所有的问题我们都已经解决。
第一版:
def FindNumsAppearOnce(self, array):
if len(array) < 2:
return None
temp = array[0]
for i in array[1:]:
temp = temp ^ i
if temp == 0:
return None
index = 0
while (temp&1) == 0:
temp = temp>>1
index += 1
num1,num2 = 0,0
for i in array:
if self.IsBit(i, index):
num1 = num1^i
else:
num2 = num2^i
return [num1,num2]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
改进版:
def FindNumsAppearOnce(self, array):
if len(array) < 2:
return None
remain, index = 0, 1
for num in array:
remain = remain ^ num
while (remain & index) == 0:
index = index << 1
res1,res2 = 0,0
for num in array:
if (num & index) == 0:
res1 = res1^num
else:
res2 = res2^num
return [res1,res2]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
思路
和那道字符串里面第一次出现唯一字符的题目类似,使用count计数方法;另外百度了一下发现还可以用collections模块的Counter方法,把列表值和对应的个数组成一个字典
方法一:
class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here targets = [] for num in array: if array.count(num)==1 and num not in targets: targets.append(num) return targets
方法二:
import collections class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here targets = [] dic = collections.Counter(array) for key,value in dic.items(): if value < 2: targets.append(key) return targets