leetcode 136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解法:
使用xor
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ """ # 3,4,5,3,4,5 # 3^3 = 0 # 4^4 = 0 # 5^5 = 0 # 0^0 = 0 # 0^0 = 0 x = nums[0] for i in range(1, len(nums)): x ^= nums[i] return x """ return reduce(lambda x,y: x^y, nums, 0)
语法
reduce() 函数语法:
reduce(function, iterable[, initializer])
参数
- function -- 函数,有两个参数
- iterable -- 可迭代对象
- initializer -- 可选,初始参数