Given an integer array nums
, where 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.
Example:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
nums
guaranteed to be integers?
1
) in the result of the XOR from step 1. This bit guarantees that the two unique numbers differ at that position.def singleNumber(nums):
# Step 1: XOR all numbers to get the XOR of the two unique numbers
xor = 0
for num in nums:
xor ^= num
# Step 2: Find a set bit in the xor (rightmost set bit)
set_bit = xor & -xor
# Step 3: Partitioning numbers and XOR-ing separately
num1, num2 = 0, 0
for num in nums:
if num & set_bit:
num1 ^= num
else:
num2 ^= num
return [num1, num2]
# Example usage
nums = [1, 2, 1, 3, 2, 5]
print(singleNumber(nums)) # Output: [3, 5]
This approach leverages the power of bit manipulation effectively to maintain linear time complexity, which is optimal for this problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?