Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

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
class Solution {
public:
int missingNumber(vector<int>& nums) {
int s = nums.size();
nums[s] = -1;
int i = 0;
while (i < s) {
if (nums[i] != -1 && nums[i] != i) {
swap(nums[i], nums[nums[i]]);
} else {
i++;
}
}

int result = nums.size();
for (int j = 0; j < nums.size(); j++) {
if (nums[j] == -1) {
result = j;
break;
}
}

return result;
}

void swap(int &a, int &b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
};