通过hashmap求解,也可以通过异或求解。
由于这道题是两个唯一的数字,所以第一轮异或结束,结果一定是非0的,根据异或结果中非0的一位来和数组中其他元素做与运算,然后分成两个数组,这样可以把两个唯一的元素分到两个数组中然后再进行异或得出答案。
为了写法更简洁些,可以不使用append,可以在开始的时候就初始化好result=[0,0],然后根据result[0],result[1] 做异或操作,结果直接放在result数组中。再根据大小调整一下就可以。
也可以将第一次异或结果与一个为1的变量进行与运算,然后左移1变量,这样就可以每次不用调整元素的值进行移位操作,直接与即可,但是比如2与2 会输出0 10和10与 最末位不是1。
所以判断条件应该为!=0
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param array int整型一维数组
# @return int整型一维数组
#
class Solution:
def FindNumsAppearOnce(self , array ):
# write code here
# hashmap={}
# for i in range(len(array)):
# if array[i] not in hashmap:
# hashmap[array[i]]=1
# else:
# hashmap[array[i]]+=1
# result=[]
# for i in hashmap:
# if hashmap[i]==1:
# result.append(i)
# if result[0]>result[1]:
# result[0],result[1]=result[1],result[0]
# return result
single=0
result=[0,0]
for i in range(len(array)):
single^=array[i]
m=1
while single&m==0:
m<<=1
for i in range(len(array)):
if m&array[i]!=0:
result[0]^=array[i]
else:
result[1]^=array[i]
if result[0]>result[1]:
result[0],result[1]=result[1],result[0]
return result
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param array int整型一维数组
# @return int整型一维数组
#
class Solution:
def FindNumsAppearOnce(self , array ):
# write code here
# hashmap={}
# for i in range(len(array)):
# if array[i] not in hashmap:
# hashmap[array[i]]=1
# else:
# hashmap[array[i]]+=1
# result=[]
# for i in hashmap:
# if hashmap[i]==1:
# result.append(i)
# if result[0]>result[1]:
# result[0],result[1]=result[1],result[0]
# return result
single=0
left=[]
right=[]
result=[0,0]
for i in range(len(array)):
single^=array[i]
n=0
while single&1==0:
n+=1
single=single>>1
# m=1
# while single&m==0:
# m<<=1
print(bin(single))
for i in range(len(array)):
temp=n
bit=array[i]
while temp>0:
bit=bit>>1
temp-=1
if single&bit==1:
result[0]^=array[i]
else:
result[1]^=array[i]
# left_single=0
# right_single=0
# for i in range(len(right)):
# right_single^=right[i]
# for i in range(len(left)):
# left_single^=left[i]
# if left_single>right_single:
# result.append(right_single)
# result.append(left_single)
# else:
# result.append(left_single)
# result.append(right_single)
if result[0]>result[1]:
result[0],result[1]=result[1],result[0]
return result

京公网安备 11010502036488号