topic
Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.
Description:
Your algorithm should have linear time complexity. You can not use the extra space to achieve it?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/single-number
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
The official solution to a problem ( method 4 too good, so I did not expect XOR can use! )
Method 4: Bit Operation
concept
If we do XOR operation to 0 and bits, still get this bit
a XOR 0 = a
, if we do XOR operation on the same binary bits, the result returned is 0
a different or a = 0
XOR commutative and associativity
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
So we only need to carry out all the numbers XOR operation, to get that unique number.
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)
complexity of space: 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)
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.