-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
41 lines (34 loc) · 1.24 KB
/
Solution.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
#include <cstddef>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
// Find the numbers that occur twice and the number that is missing.
// XOR and sum (since 1 to n)
// XOR with [1..n] and nums[i]. This ensures that every number that
// appears once will be XOR-ed a total of two times, effectively resulting
// in 0, whereas the number that appears twice will be XOR-ed three times.
// However, the missing number will be XOR-ed once.
// Thus, another approach is necessary.
// This requires exploiting the property that the numbers lie in the
// range [1..n].
// Thus, by modifying the array in-place, the duplicate number can be
// figured out.
const int n = nums.size();
int duplicateNumber = 0;
int missingNumber = (n * (n + 1)) / 2;
for (int i = 0; i < n; ++i) {
// num is 1-indexed
const int num = abs(nums[i]);
if (nums[num - 1] < 0) {
// A previous iteration already flipped this position
duplicateNumber = num;
}
// Flip the number pointed to by num
nums[num - 1] *= -1;
missingNumber -= num;
}
return {duplicateNumber, missingNumber + duplicateNumber};
}
};