https://leetcode.com/problems/missing-number/
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
.
class Solution {
public:
int missingNumber(vector<int>& nums) {
// the greatest number is n
int n = nums.size();
for(int i=0; i<n; ++i) {
while(nums[i] != i) {
if(nums[i]<n) {
int t = nums[i];
nums[i] = nums[t];
nums[t] = t;
} else {
break;
}
}
}
for(int i=0; i<n; ++i) {
if(nums[i] != i) {
return i;
}
}
}
};
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = 0;
for(int i=0; i<nums.size(); ++i) {
n ^= nums[i]^i;
}
return n^nums.size();
}
};