260. Single Number III
Explanation
To solve this problem, we can use the concept of bit manipulation. We know that if we XOR all the elements in the array, we will end up with XOR of the two numbers that appear only once. Let's say this XOR result is xorResult
.
Now, we need to find a way to separate these two numbers and for that, we can use the rightmost set bit in xorResult
. This rightmost set bit is different for the two numbers that appear only once. We can divide the array elements into two groups based on this rightmost set bit.
After dividing the elements, we can XOR all the elements in each group to find the two numbers that appear only once.
class Solution {
public int[] singleNumber(int[] nums) {
int xorResult = 0;
for (int num : nums) {
xorResult ^= num;
}
int rightmostSetBit = xorResult & (-xorResult);
int[] result = new int[2];
for (int num : nums) {
if ((num & rightmostSetBit) == 0) {
result[0] ^= num;
} else {
result[1] ^= num;
}
}
return result;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.