Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

假設一個數組中除了一個數只出現一遍外,其他的都出現兩遍,找出這個只出現一遍的數。

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not any(nums):
            return None
        ret = nums[0]
        for i in range(1,len(nums)):
            ret ^= nums[i]
        return ret
        
用異或運算(XOR),太騷氣了。

A^A=0

A^B^A=B

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章