编程语言:
python
题目:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例:
输入: [2,2,1]
输出: 1
输入: [4,1,2,1,2]
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
解法:
1、使用列表的count方法——>得到某个数字出现的次数int(空间复杂度较低)
2、使用collections中的Counter函数——>得到统计所有数字出现次数的字典(时间复杂度较低)
3、使用位运算求解——>nums数组中所有数进行位运算,最终得到的就是只出现一次的数字
代码:
#解法一:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
for i in nums:
if nums.count(i) == 1:
return i
#解法二:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = Counter(nums)
n = len(nums)
for i in nums:
if ans[i] == 1:
return i
#解法三:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x ^ y, nums)