Leetcode 260. Single Number III
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. Your algorithm should run in linear runtime complexity and use only constant extra space.
nums
?
nums
?
To solve the problem with a time complexity of O(n) and space complexity of O(1), we can use the following strategy:
This will give us the two numbers that appear only once.
public class Solution {
public int[] singleNumber(int[] nums) {
// Step 1: Get the XOR of the two unique numbers
int xor = 0;
for (int num : nums) {
xor ^= num;
}
// Step 2: Get the rightmost set bit in the xor result
int rightmostSetBit = xor & -xor;
// Step 3: Divide numbers into two groups and XOR within each group
int num1 = 0, num2 = 0;
for (int num : nums) {
if ((num & rightmostSetBit) == 0) {
num1 ^= num; // XOR in the first group
} else {
num2 ^= num; // XOR in the second group
}
}
// The result array containing the two unique numbers
return new int[]{num1, num2};
}
}
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?