[LEETCODE]268. 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.
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.
这道题一开始用了O(n) 复杂度,但是空间做不到O(1) ,这个方法类似hash,用一个数组来记录位置,如果出现了则把该位置置为true,最后扫一遍就可以得到为false 的值。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int size = nums.size();
if (size == 0) return 0;
vector<bool> has(size + 1, false);
for (int i = 0; i < size; i++) {
has[nums[i]] = true;
}
for (int i = 0; i < has.size(); i++) {
if (has[i] == false) return i;
}
return size;
}
};
然后发现一个非常简单的方法。用的是等差数列求和,如果然后减掉nums 的值,剩下来的就是缺失的值。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int expect = (n+1) * n / 2;
for(int i = 0; i < n; i ++)
expect -= nums[i];
return expect;
}
};