Skip to content

136 single number

136. Single Number

题目: https://leetcode.com/problems/single-number/

难度:

Easy

思路:

位运算,终于要take it了

非常常见的一道算法题,将所有数字进行异或操作即可。对于异或操作明确以下三点:

  • 一个整数与自己异或的结果是0
  • 一个整数与0异或的结果是自己
  • 异或操作满足交换律,即a^b=b^a

Python的位操作: https://wiki.python.org/moin/BitwiseOperators

神奇的解法:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = nums[0]
        for i in nums[1:]:
            res ^= i
        return res

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组