给一个整型数组,其中只有一个元素出现1次,其余元素都出现两次,让你找出只出现一次的元素
注意:
使用线性的运行时间,不使用额外的空间
(这里解释一下,leetcode中线性时间即O(n),不使用额外的空间就是空间复杂度为O(1))
直接粘代码吧:
class Solution(object):
def singleNumber(self, nums):
length = len(nums)
i =1
while i < length:
nums[0] = nums[0]^nums[i]
i += 1
return nums[0]
解释下用到的知识点,就是位运算的异或(^)运算。相同的数异或后为0 ,最后就剩下那个只出现一次的数
例如:
2 ^ 2 = 0
2^2^1 =1