-
Notifications
You must be signed in to change notification settings - Fork 110
/
136-single-number.cpp
59 lines (55 loc) · 1.21 KB
/
136-single-number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Hashset method
// O(n) time | O(n) space
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_set<int> s;
for (int i = 0; i < nums.size(); i++)
{
int curr = nums[i];
if (s.find(curr) == s.end())
{
s.insert(curr);
}
else
{
s.erase(curr);
}
}
return *(s.begin());
}
};
// Math method
// O(n) time | O(n) space
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_set<int> s;
int actualSum = 0;
int doubleSum = 0;
for (int i = 0; i < nums.size(); i++)
{
int curr = nums[i];
actualSum += curr;
if (s.find(curr) == s.end())
{
s.insert(curr);
doubleSum += curr + curr;
}
}
return doubleSum - actualSum;
}
};
// Bit manipulation
// O(n) time | O(1) space
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int i = 0; i < nums.size(); i++)
{
res ^= nums[i];
}
return res;
}
};