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?
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
if (len==1) {
return nums[0]==1?0:1;
}
sort(nums.begin(), nums.end());
if (nums[0]!=0) {
return 0;
}
for (int i=1; i<len; i++) {
if (i==0&&nums[i]!=0) {
return 0;
}
if (nums[i]!=nums[i-1]+1) {
return nums[i]-1;
}
}
return nums[len-1]+1;
}
};
第二种解法:
```c++
class Solution {
public:
int missingNumber(vector& nums) {
int result = nums.size();
int i=0;
for(int num:nums){
result ^= num;
result ^= i;
i++;
}
return result;
}
};
```