LeetCode 260: Single Number III Solution
Master LeetCode problem 260 (Single Number III), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
260. Single Number III
Problem Explanation
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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 260 (Single Number III)?
This page provides optimized solutions for LeetCode problem 260 (Single Number III) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 260 (Single Number III)?
The time complexity for LeetCode 260 (Single Number III) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 260 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 260 in Java, C++, or Python.