Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1
Input: [3,0,1] Output: 2
Example 2
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
思路:
1. 数学方法,因为已知是0-n范围中缺少一个,所以若不缺少,和为0++1+2+……+n。所以求出目标和,然后减去现有数组的和,即为缺少的那个数;
2. 异或运算xor,
0 ^ a = a ^ 0 =a
a ^ b = b ^ a
a ^ a = 0
0到size()间的所有数一起与数组中的数进行异或运算,因为同则0,0异或某个未出现的数将存活下来。
3. 数组index作为标记
代码1:
class Solution {
public:
int missingNumber(vector<int>& nums) {
nums.push_back(1);
int index, result;
for(int i=0;i<(nums.size()-1);i++){
index = abs(nums[i]);
if(nums[index]>0){
nums[index]=-nums[index];
}
}
for(int i=0;i<nums.size();i++){
if(nums[i]>=0){
if(nums[i]!=0){
return i;
}
else {result = i;}
}
}
return result;
}
};
代码2:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
int res = (0+len)*(len+1)/2;
int sum=0;
for(int i:nums){sum += i;}
return res-sum;
}
};
代码3:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = 0;
for (int i = 1; i <= nums.size(); i++)
res =res ^ i ^ nums[i-1];
return res;
}
};