Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
给定一个非空的整数数组,除了一个元素外,每个元素都会出现两次。 找到那一个。
注意:
您的算法应具有线性运行时复杂性。 你能不用额外的内存来实现吗?
例1:
输入:[2,2,1]
输出:1
例2:
输入:[4,1,2,1,2]
输出:4
代码:
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in nums:
res ^= i
return res
思路:
两个相同的数异或为0 任何数和0异或是这个数本身 所以直接异或遍历一遍就可以得到这个单独的数。