题目:
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?
题意:
从0,1,2..n中抽出n个数,找出哪一个数没有被抽中。
思路:
- 最简单的方法是将这n个数加起来,再用原来的n+1个数的和即n*(n+1)/2,减去这n个数的和。
但是这种题目,容易考的是当这些数累加起来会溢出。我采用的做法是使用long long保存中间结果,并且不是将所有的数累加起来再减去,我是一边添加那n个数,一边从0-n依次减去。比如原来数字是0,1,2,3,4,5,6;抽了一个数之后是1,2,3,4,5,6,那么我在对后面每一个数字往里面添加时(依次1,2,3,4,5,6)的同时,会减去前面每一个数字(依次减去0,1,2,3,4,5,6)。这两个加减是同时进行的。
以上。
代码如下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
long long result = 0;
int i = 0;
for(auto num:nums) {
result += i;
result -= num;
i++;
}
result += i;
return result;
}
};
2.当然我们也可以采用位操作的方法,对于原始数组A,元素是0-n,对于抽取的数组B,元素是A中的元素少了一个。所以A,B两个数组合起来就是B中的元素都出现两次,另一个缺失的元素只出现一次。所以A,B中所有的元素异或起来的结果就是我们需要找的missing value。
以上。
代码如下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = 0;
for(auto num:nums)
result ^= num;
int n = nums.size();
for(int i = 0; i < nums.size() + 1; i++)
result ^= i;
return result;
}
};