牛客网-数组只出现一次的数字(异或)
题目描述:
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
自己提交代码:
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
result = []
for num in array:
if num not in result:
result.append(num)
else:
result.remove(num)
return result
提升代码:
对所有元素进行异或,结果是两个无重复数字的异或和。(相同数字的异或值为0)。因此根据异或结果将这两个数字分开(根据异或结果第一个为1的位数,将此位都为1的放一起,不为1的放一起,然后对这两组进行异或可以分别得到这两个没有重复的数字)。
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
if len(array)==2:
return array
temp = 0
for i in array:
temp ^= i
index = self.FindFrist(temp)
a,b=0,0
for num in array:
if self.bitFind(num,index)==1:
a ^= num
else:
b ^= num
return [a,b]
def FindFrist(self,temp):
index = 0
while(temp&1==0 and index<32):
temp >>= 1
index += 1
return index
def bitFind(self,temp,index):
temp >>= index
return 1 if temp&1==1 else 0

浙公网安备 33010602011771号