在缺数问题中:
Find the missing number in given integer array of 1 to 100?
下面是针对这个问题的python代码:
n无法预定义,因为它取决于在函数中分配的数组
def missingNumber(nums):
n = len(nums)
total = (n+1)*(n+2)/2
missing = total - sum(nums)
return missing
missingNumber([1, 2, 4, 5, 6])
我不明白怎么想出这样的逻辑
^{pr2}$
Tags:
你知道,在一个连续的数字数组中缺少一个数字
假设你知道前n个数的和。设前n个数之和为s。既然前n个数中缺少一个数,我们可以得到缺失数为
s - sum of remaining numbers
现在让我们看看如何计算s
比如说“1,4,100
现在我要计算它们的和
我能做的一件事就是要么把它输入计算机程序/计算器,要么一个一个地求和。在
当老师问小高斯这个问题时,他想到的另一个方法是
let s1 = 1 + 2 + 3 + ... + 100
take the reverse of it,
let s2 = 100 + 99 + 98 + ... + 1
Now add s1 and s2
s1 + s2 = (100 + 1) + (99 + 2) + .... + (1 + 100)
but s1 = s2, so,
2s1 = 101 + 101 + ... + 101 // sequence has 100 terms
{cd9}
所以我们得到了,前n个数的和是
(n)*(n+1)/2
,这是一种广义的方法。这也可以用数学归纳法加以证明。在对于您的问题,如果n是缺少数字的数组的长度,那么n+1必须是原始数组的大小。所以
s = (n+1)*(n+2)/2
你不应该用n作为论点。它将引发错误。 TypeError:missingNumber()缺少1个必需的位置参数:“n”
n在后面的函数中定义。在
函数中也有错误。在
例如,如果num=[1,2,3,4,5,6],则输出将为7 但你的阵法应该在6点结束。在
您问题的答案:-
(n+1)*(n+2)/2是第一个n+1自然数的和
如果你想找到一个丢失的号码,这里是代码
如果您愿意找到多个缺失的数字,那么下面的代码可能会有所帮助
^{pr2}$两个代码都假设输入总是以1开头,并以1为步长递增。在
相关问题 更多 >
编程相关推荐