Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
Output: [3, 5]
Explanation: 3 and 5 each appear once; 1 and 2 appear twice.
Output: [-1, 0]
Explanation: Both -1 and 0 appear once.
XOR all numbers to get xor = a ^ b where a and b are the two unique numbers. Since a != b, xor != 0. Find any set bit in xor (e.g., the lowest set bit using xor & (-xor)). Use this bit to partition numbers into two groups — a and b will fall in different groups. XOR each group separately to recover a and b.
- XOR all numbers to get xor = a ^ b.
- Find the lowest set bit:
diff = xor & (-xor). - Partition numbers into two groups based on whether this bit is set.
- XOR within each group yields a and b respectively.
Complexity Analysis:
Time complexity: O(n) — two passes through the array.
Space complexity: O(1) — constant extra space.