【python实现】 136. 只出现一次的数字
解答:
V1.0

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        s = []
        n = sorted(nums)
        for i in range(1, len(n)):
            if n[i-1] == n[i]:
                s.append(n[i])
        for i in range(len(s)):
            n.remove(s[i])
        for i in range(len(s)):
            n.remove(s[i])
        return n[0]        

V2.0

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        s = []
        n = sorted(nums)
        for i in range(1, len(n)):
            if n[i-1] == n[i]:
                s.append(n[i])
        for i in range(len(n)):
            if n[i] not in s:
                return n[i]

大神的解答:

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

总结:
异或^ :当两对应的二进位相异时,结果为1。0异或任何数不变,任何数与自己异或为0。

方法remove()只删除第一个指定的值。

相关文章:

  • 2021-11-28
  • 2021-11-14
  • 2021-09-24
  • 2021-11-06
  • 2021-12-22
  • 2021-10-21
  • 2021-08-27
  • 2021-08-16
猜你喜欢
  • 2022-02-28
  • 2021-07-11
  • 2022-01-22
  • 2021-04-21
  • 2021-04-06
  • 2021-05-08
相关资源
相似解决方案