给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
题目要求找出只出现过一次的那个元素,一种方法是首先使用set进行去重,然后依次判断set中的元素在数组中出现的次数,。直到找到那个只出现一次的元素。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []: return None
n = list(set(nums))
for i in n:
if nums.count(i) == 1:
return i
或者依次访问数组中的元素,并使用另一个数组存放已访问过的元素。如果当前访问元素在数组中不存在,则将其加入到数组中;如果已存在,则将其从数组中移除。最后返回数组的最后一个元素,即只出现了一次的元素。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []: return None
stack = []
for i in nums:
if i not in stack:
stack.append(i)
else:
stack.remove(i)
return stack[-1]
或者是利用字典来保存访问的元素,如果当前访问元素在字典中不存在则将其加入字典,否则将其从字典移除,最后返回字典的中最后一个元素的键。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []: return None
d = {}
for i in nums:
if i not in d.keys():
d[i] = 1
else:
d.pop(i)
return d.popitem()[0]
或者使用计数器函数Counter()来统计数组中的元素及其对应的出现次数,然后依次遍历找到值等于1的键即可。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []: return None
d = Counter(nums)
for k in d.keys():
if d[k] == 1:
return k
位运算法
异或 ⊕ \oplus ⊕d的运算规律是:
- 如果 a a a和 b b b相同,则异或结果为1
- 如果 a a a和 b b b不同,则异或结果为0
运算法则有:
- a ⊕ 0 = a a \oplus 0 = a a⊕0=a
- a ⊕ a = 0 a \oplus a = 0 a⊕a=0
- a ⊕ b = b ⊕ a a \oplus b = b \oplus a a⊕b=b⊕a
- a ⊕ b ⊕ c = a ⊕ ( b ⊕ c ) = ( a ⊕ b ) ⊕ c a \oplus b \oplus c = a \oplus (b \oplus c) = (a \oplus b) \oplus c a⊕b⊕c=a⊕(b⊕c)=(a⊕b)⊕c
- a ⊕ b ⊕ a = 0 a \oplus b \oplus a = 0 a⊕b⊕a=0
因此将所有数进行异或操作就可以得到唯一的数字。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
参考 官方题解