只出现一次的数字(力扣 | 初级算法 | 数组 | Python)

一、题目描述

在这里插入图片描述

二、代码解析

解法一:异或运算

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

# solution = Solution()
# result = solution.singleNumber([4,1,2,1,2])
# print(result)

注:两个数的异或,是两个数对应的二进制形式的异或。异或的意思是相异则为1,相同则为0,即两个相同的数异或为0,而0和任何数的异或都是这个数本身。

三、总结

官方题解链接可以点这里。这个题的最佳解法是异或运算,当然也可以发散思维,尝试其它方法。

猜你喜欢

转载自blog.csdn.net/qq_40968179/article/details/128516110