# Python different solutions.

• def singleNumber1(self, nums):
dic = {}
for num in nums:
dic[num] = dic.get(num, 0)+1
for key, val in dic.items():
if val == 1:
return key

def singleNumber2(self, nums):
res = 0
for num in nums:
res ^= num
return res

def singleNumber3(self, nums):
return 2*sum(set(nums))-sum(nums)

def singleNumber4(self, nums):
return reduce(lambda x, y: x ^ y, nums)

def singleNumber(self, nums):
return reduce(operator.xor, nums)

• singleNumber1 and singleNumber3 are not space O(1)

• Yes, the typical solution should be singleNumber2(). Here I just want to inspire more idea.

• learn a lot from these solutions

• It will be better for singleNumber1 to use set than dict

• It will be better for singleNumber1 to use set than dict

• How does the ^= operator work? As in, what does it do?

• @rkania3 Beacuse n^n=0.so the xor of all elements = 0^0^0....^(single_number) = single_number

• You can replicate the behavior of singleNumber1() by using the Counter class from the collections module. Lines 2-4 are replaced by dlc = Counter(nums).

• very　ｆｕｃｋｉｎｇ　good

• the xor solution is great

• Really Good Summay!

• from collections import Counter

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = Counter(nums)
for k,i in a.items():
if i < 2:
return k

• class Solution(object):
def singleNumber(self, nums):
singleNum=[]
while nums:
n=nums.pop()
if n in nums:
nums.remove(n)
else:
singleNum.append(n)
return singleNum

• Should the return statement in singleNumber2 be:
'''
return res ^ 0
'''
?

• @caikehe Very delicate solution using the xor operation, thank you!

• the first solution could be optimized like:

def singleNumber1(self, nums):
dic = {}
for num in nums:
if dic.get(num, 0):
dic.pop(num)
else:
dic[num] = 1
return list(dic)[0]

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.