LeetCode----Single Number

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?


分析:

找出数组中仅仅出现过一次的数,数组中其他的数均出现过两次。要求在线性时间中完成,不借助额外的空间。

这题想了一会没有写出来,看了题目的tags,标注了Bit manipulation,即可以使用位运算来做。随即想起了位运算的异或操作,有A^B^A = B。

借助Python中的reduce,可以一行代码完成运算。


代码:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return reduce(lambda x, y: x ^ y, nums)

你可能感兴趣的:(位运算,LeetCode,python)