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
题意
找出一个非空数组中只出现一次的数字,除了这个数,其他数都出现了两次。
思路
位运算。
相同的数异或为0,一个数异或0为它本身。
代码
class Solution:
def singleNumber(self, nums):
res = 0
for i in nums:
res ^= i
return res
网友评论