Single Number
You are given a non-empty array of integers nums. Every integer appears twice except for one.
Return the integer that appears only once.
You must implement a solution with O(n)O(n)O(n) runtime complexity and use only O(1)O(1)O(1) extra space.
Example 1:
Input: nums = [3,2,3]
Output: 2
Example 2:
Input: nums = [7,6,6,7,8]
Output: 8
Constraints:
1 <= nums.length <= 10000
-10000 <= nums[i] <= 10000
Solution
The key idea of this problem is to find an operation that can transform 2 identical numbers into a constant, while when the constant is operated with another number, the value of the number doesn’t change.
Operation XOR ⊕\oplus⊕ has such properties that
a⊕a=00⊕a=a
a \oplus a = 0\\
0 \oplus a = a
a⊕a=00⊕a=a
When XOR operation is applied to the whole list, each identical number pair will cancel each other. Therefore, the remaining number with be the only single one.
Code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for num in nums:
ans ^= num
return ans