forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-the-missing-number.cpp
More file actions
35 lines (33 loc) · 927 Bytes
/
find-the-missing-number.cpp
File metadata and controls
35 lines (33 loc) · 927 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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param nums: a vector of integers
* @return: an integer
*/
int findMissing(vector<int> &nums) {
int missing_num = 0;
// xor all nums <= N.
for (int num = 0; num <= nums.size(); ++num) {
missing_num ^= num;
}
// Delete num in nums.
for (const auto& num : nums) {
missing_num ^= num;
}
// The remaining num would be missing num.
return missing_num;
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
int findMissing(vector<int> &nums) {
vector<int> expected(nums.size());
iota(expected.begin(), expected.end(), 1); // Costs extra space O(n)
return accumulate(nums.cbegin(), nums.cend(), 0, bit_xor<int>()) ^
accumulate(expected.cbegin(), expected.cend(), 0, bit_xor<int>());
}
};