-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_17.19_missingTwo.cc
90 lines (82 loc) · 1.35 KB
/
Problem_17.19_missingTwo.cc
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <algorithm>
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int lowBit(int x) { return x & -x; }
vector<int> missingTwo(vector<int>& nums)
{
int xorSum = 0;
int N = nums.size() + 2;
for (int n : nums)
{
xorSum ^= n;
}
for (int i = 1; i <= N; i++)
{
xorSum ^= i;
}
// xorSum = a ^ b
int lowbit = lowBit(xorSum);
int a = 0, b = 0;
for (int n : nums)
{
if (n & lowbit)
{
a ^= n;
}
else
{
b ^= n;
}
}
for (int i = 1; i <= N; i++)
{
if (i & lowbit)
{
a ^= i;
}
else
{
b ^= i;
}
}
return {a, b};
}
};
bool isVectorEqual(vector<int> a, vector<int> b)
{
if (a.size() != b.size())
{
return false;
}
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
for (int i = 0; i < a.size(); i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
void testMissingTwo()
{
Solution s;
vector<int> in1 = {1};
vector<int> out1 = {2, 3};
vector<int> in2 = {2, 3};
vector<int> out2 = {1, 4};
EXPECT_TRUE(isVectorEqual(out1, s.missingTwo(in1)));
EXPECT_TRUE(isVectorEqual(out2, s.missingTwo(in2)));
EXPECT_SUMMARY;
}
int main()
{
testMissingTwo();
return 0;
}