Skip to content

Commit 32d97e8

Browse files
authored
Create 136_single_number.cpp
1 parent b523667 commit 32d97e8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

solutions/136_single_number.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//Solution-1:
2+
//Time: O(nlogn), Space: O(1)
3+
class Solution {
4+
public:
5+
int singleNumber(vector<int>& nums) {
6+
sort(nums.begin(), nums.end());
7+
if(nums.size()==1){
8+
return nums[0];
9+
}
10+
int i=0,res = 0;
11+
while(i<nums.size()-1){
12+
if(nums[i] == nums[i+1]){
13+
i+=2;
14+
}
15+
else{
16+
res = i;
17+
break;
18+
}
19+
if(i==nums.size()-1){
20+
res = i;
21+
}
22+
}
23+
return nums[res];
24+
}
25+
};
26+
27+
//Solution-2: Using Bitwise XOR operation
28+
//Time: O(n), Space: O(1)
29+
class Solution {
30+
public:
31+
/*
32+
XOR's properties,
33+
1. a^a=0
34+
2. a^b^a=b
35+
3. (a^a^b) = (b^a^a) = (a^b^a) = b
36+
4. Similarly, a^a^a.... (even times)=0 and a^a^a....(odd times)=a
37+
*/
38+
int singleNumber(vector<int>& nums) {
39+
int res = 0;
40+
for(auto x: nums){
41+
res^=x;
42+
}
43+
return res;
44+
}
45+
};

0 commit comments

Comments
 (0)