题目:
Given an 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?
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
res = []
nums.sort()
for num in nums:
if num in res :
res.remove(num)
else:
res.append(num)
return res[0]
python解法二:
看到的别人的解法,采用按位异或的思想,对应的二进制位相同则为0,非常聪明。
class Solution:
def singleNumber(self, nums):
cal=0
for i in nums:
cal ^= i
return cal