做题是真快乐呀-【异或】136. 只出现一次的数字

liqi175 / 2024-03-20 / 原文

题目:136. 只出现一次的数字

我的思路:

  • 遍历一遍,做哈希映射。
  • 再遍历一遍,找到结果为1的那个,就是答案

我的代码:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        dic = {}
        for i in nums:
            dic[i] = dic.get(i,0) + 1
        ans = 0
        for k,v in dic.items():
            if v ==1:
                ans = k
                break
        return ans

结果截图:

改进&感悟:

  • 看了别人的题解,居然可以用【异或】这个思路。
  • AI:什么是异或?

扩展思路&代码:

  • 利用异或的性质:
  • a ^ a = 0
  • a ^ 0 = a

代码:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        # 利用异或来做题
        ans = 0
        for i in nums:
            ans = ans ^ i
        return ans

(怎么还慢了呢)

灵神的写法:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        # 利用异或来做题
        # 用reduce
        return reduce(xor,nums)

(原来是加了注释影响了速度呀)

参考资料:

AI:什么是异或?

灵山题解:https://leetcode.cn/problems/single-number/solutions/2481594/li-yong-yi-huo-de-xing-zhi-fu-ti-dan-pyt-oizc