leetcode 第136题:只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
本题官方题解是使用位运算的解法:
## Input: [1, 2, 2, 3, 3]
## Output: 1
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x^y, nums)
其中涉及到 reduce 函数和 lambda 函数的用法,参见知乎链接
当然也可以使用先排序再遍历的方法和先去重再寻找的方法:
先排序再遍历
## Input: [1, 2, 2, 3, 3]
## Output: 1
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
for i in range(0, len(nums)-1, 2):
if nums[i] != nums[i+1]:
return nums[i]
return nums[-1]
先去重再寻找
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2*sum(set(nums)) - sum(nums)