Open
Description
# 1
from functools import reduce
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
Ltype nums: List[int]
:rtype: int
"""
return reduce(lambda x,y: x ^ y, nums)
# 2
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
Ltype nums: List[int]
:rtype: int
"""
return 2 * sum(set(nums)) - sum(nums)
- reduce() 是 Python 的内置函数,但在 Python3 开始,需要调包。在 lambda 函数里面,运用了异或运算符进行计算。
- 方法 2 是数学方法,有些讨巧。
Metadata
Metadata
Assignees
Labels
No labels