-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleNumber.cpp
More file actions
46 lines (43 loc) · 968 Bytes
/
Copy pathSingleNumber.cpp
File metadata and controls
46 lines (43 loc) · 968 Bytes
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
//task 136
//24ms 9.7mb
//check near element solution
class Solution {
public:
int singleNumber(vector<int>& nums)
{
if (nums.size() == 1) return nums[0];
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 1; i+=2)
{
if (nums[i] != nums[i+1]) return nums[i];
}
if (nums[nums.size() - 2] != nums[nums.size() - 1]) return nums[nums.size() - 1];
return 0;
}
};
//xor and range-based loop solution
class Solution {
public:
int singleNumber(vector<int>& nums)
{
int x = 0;
for (auto el : nums) x = x^el;
return x;
}
};
//flip-flop element sign solution
class Solution {
public:
int singleNumber(vector<int>& nums)
{
sort(nums.begin(), nums.end());
int result = 0;
int i = -1;
for (auto el : nums)
{
result += el*i;
i *= -1;
}
return abs(result);
}
};