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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:给定的完整的nums是0-n之间连续的数,但是现在缺少了某一个,因此完整的sum(nums) = size*(size+1)/2,size = nums.size(),因此将nums中的数求和,然后用sum(nums)减去,得到的结果即为缺失的数,代码如下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int size = nums.size();
int res = 0;
for(int i = 0; i < size; ++i){
res += nums[i];
}
return size*(size+1)/2 - res;
}
};
换个思路,前面做了Single Number这道题,使用的是异或操作,因此可以将思路用到本题上,将[1,size]分别与nums中的每一个一个元素进行异或运算,由于缺失的元素只会出现一次,而不会缺失的元素会出现两次,故最后得到的结果就是缺失的元素,代码如下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int size = nums.size();
int res = 0;
for(int i = 0; i < size; ++i){
res ^= (i+1) ^ nums[i];
}
return res;
}
};