# 消失的数字(面试题 17.04)

# 题目

数组nums包含从0到n的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。

你有办法在O(n)时间内完成吗?

注意:本题相对书上原题稍作改动

# 示例

输入:[3,0,1] 输出:2

输入:[9,6,4,2,3,5,7,0,1] 输出:8

# 算法

# 暴力法

export const missingNumber = (nums) => {
	const isAppear = [];
	nums.forEach((num) => (isAppear[num] = true));
	for (let i = 0; i < isAppear.length; i++) {
		if (!isAppear[i]) return i;
	}
	return isAppear.length;
};
1
2
3
4
5
6
7
8

# 数学法

参数数组nums长度为n,则不缺失的数组长度应为n+1

这个数组不消失数字时,平均值应该是max(nums) / 2

如果把任意一个数字改为0(假装他消失了),此时数组的平均值是sum(nums) / (n+1)

我们用不消失数字应该有的平均值减去消失了数字的平均值的差,乘以不消失数字的数组长度,得到的值就是消失的数字

export const missingNumber = (nums) => {
	if (nums.length - 1 === nums[nums.length - 1]) return nums[nums.length - 1] + 1;
	const curAvg = nums.reduce((acc, cur) => (acc += cur)) / (nums.length + 1);
	const actualAvg = nums.length / 2;
	return (actualAvg - curAvg) * (nums.length + 1);
};
1
2
3
4
5
6