Use bitwise XOR operation. XORing a number with itself yields 0, so XORing all elements together cancels duplicates and leaves the single number.
def singleNumber(nums):
res = 0
for n in nums:
res ^= n
return res
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int n : nums) {
res ^= n;
}
return res;
}
}