Loading content...
Created On: December 2, 2023
Using set we can find the required result as set has the property that it doesn't store any duplicate number.
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
set<int> set;
int a=0, b=0;
//inserting all the nums in the set
//and computing the sum of all the nums
for(auto x: nums){
set.insert(x);
b+=x;
}
//now re-computing the sum of all the unique elements
//present in the set and since every duplicate number has
//frequncy equals to 2 so by multiplying the sum we will get
//the sum if all the nums are duplicate
for(auto x: set)
a+=x;
a = a*2;
//now if we divide the sum a and b we will get the num
//that appears only once
return a-b;
}
};We can also use the bit manipulation properties.
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(auto x: nums)
//by using xor operator we can find
//the num that appear only once
res^=x;
return res;
}
};