一、刷题内容
原题链接
https://leetcode-cn.com/problems/single-number/
内容描述
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
二、解题方案
1.方法一
这个方法所需时间巨长。用time模块跟方法二对比,慢了160倍。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
while len(nums) > 0:
res = nums.pop(0)
if res in nums:
nums.remove(res)
else:
return res
2.方法二
异或
直接使用异或操作。
满足交换律: a ^ b ^ c == a ^ c ^ b
任何数异或于0都为它本身: 0 ^ n == n
相同的数字异或为0: n ^ n ==0
神奇的位运算!!!
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for num in nums:
# 0 ^ 4 ^ 1 ^ 2 ^ 1 ^ 2 == 4
res = res ^ num
return res
3.方法三
方法二的一行写法
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda x,y:x^y,nums)