一、题目描述
二、代码解析
解法一:异或运算
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in range(len(nums)):
result = result^nums[i]
return result
# solution = Solution()
# result = solution.singleNumber([4,1,2,1,2])
# print(result)
注:两个数的异或,是两个数对应的二进制形式的异或。异或的意思是相异则为1,相同则为0,即两个相同的数异或为0,而0和任何数的异或都是这个数本身。
三、总结
官方题解链接可以点这里。这个题的最佳解法是异或运算,当然也可以发散思维,尝试其它方法。