LeetCode 136 Single Number (Python)

Posted by 小明MaxMing on April 26, 2020

题目

Given a non-empty 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?

解题思路

对于异或运算,我们知道 a^a=0; a^0=a,所以我们就把所有的数都异或到一起,那么所有出现两次的数就会是0,只留下最后一个只出现过一次的数字了。

代码

import functools
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return functools.reduce(lambda x, y: x ^ y, nums)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅