Tencent 30-leetcode136 that only appears once
Be familiar with
XOR on XOR and exchange law, satisfy exchange law and union law
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
we XOR the same binary bit, the returned result is 0
XOR satisfies the exchange law and the combination law
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.