Leetcode - 136 - Python

给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。 备注:你的算法应该是一个线性时间复杂度。 你可以不用额外空间来实现它吗?

嘛…我自己写的又超时了…

def sad(nums):

    c = 0

    for i in range(len(nums)):

        for j in range(len(nums)):

            if nums[i] == nums[j]:

                c = c + 1

        if c !=2:

            return nums[i]

        else:

            c = 0


以下是大神的答案

classSolution(object): 

     defsingleNumber(self, nums):

        res = 0        

        for i in nums:

            res ^= i

        return res

你可能感兴趣的:(Leetcode - 136 - Python)