Leetcode 136 利用异或运算寻找出现奇数次的数

今天在水Leetcode的简单题时,遇到一道题让我从一个数字列表中找出只出现一次的数,其他的数均出现两次。

题目链接:https://leetcode-cn.com/problems/single-number/description/

我的思路就非常水了,排个序,左右比较一下,然后总感觉还有更好的方法,就去搜了一下,果然,又学到了。网上的大佬都用异或运算来解决道题目。

异或的特点:

a xor b xor a == b

利用这个特点,只要拿第一个数字一路异或下去,就能剩下只出现一次的数字,进一步说,可以得到出现奇数次的数字(前提是其他数字都出现偶数次)

上个代码:

#encoding=utf-8
import numpy as np

# (a xor b) xor a = b
# a xor b xor c xor a xor c
#=(a xor (b xor c) xor a) xor c
#=(b xor c) xor c
#=b
#正好剩下出现奇数次的数
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        a = nums[0]
        for i in range(1, n):
            a = a ^ nums[i]
        return a

猜你喜欢

转载自blog.csdn.net/ZouCharming/article/details/81711330