Tencent 30-a number that only appears once

Tencent 30-leetcode136 that only appears once

Be familiar with
XOR on XOR and exchange law, satisfy exchange law and union law
a b a = ( a a ) b = 0 b = b a⊕b⊕a=(a⊕a)⊕b=0⊕b=b

2 * (a + b + c) - (a + a + b + b + c) = c2∗(a+b+c)−(a+a+b+b+c)=c

Python
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return 2 * sum(set(nums)) - sum(nums)

Complexity analysis

Time complexity: O (n + n) = O (n) O (n + n) = O (n). sum will call next to traverse the elements in \ text {nums} nums. We can think of the above code as sum (list (i, for i in nums)), which means that the time complexity is O (n) O (n), because the number of elements in \ text {nums} nums is nn Pcs.
Space complexity: O (n + n) = O (n) O (n + n) = O (n). The space required by set is equal to the number of elements in nums.
Method 4: Bit manipulation
concept

If we XOR the 0 and the binary bit, we still get this binary bit
a 0 = a a⊕0=a
we XOR the same binary bit, the returned result is 0
a a = 0 a⊕a=0
XOR satisfies the exchange law and the combination law
a b a = ( a a ) b = 0 b = b a⊕b⊕a=(a⊕a)⊕b=0⊕b=b

So we only need to XOR all the numbers to get the unique number.

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

Complexity analysis

Time complexity: O (n) O (n). We only need to traverse the elements in \ text {nums} nums once, so the time complexity is the number of elements in \ text {nums} nums.
Space complexity: O (1) O (1).

Author: LeetCode
link: https: //leetcode-cn.com/problems/single-number/solution/zhi-chu-xian-yi-ci-de-shu-zi-by-leetcode/
Source: stay button (LeetCode)
The copyright belongs to the author. For commercial reproduction, please contact the author for authorization, and for non-commercial reproduction, please indicate the source.

Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103646618