【发布时间】:2020-03-09 00:38:30
【问题描述】:
我在一次采访中被问到这个问题:给你一组数字 {1..N} 和一个数组 A[N-1]。从集合中找出数组中不存在的数字。下面是我到目前为止的代码和伪代码,它不起作用。
我假设集合中有一个(并且只有一个)不在数组中的数字
- 遍历集合中的每个元素
- 遍历数组中的每个元素 O(n)
- 检查数字是否在数组中
- 如果是,什么也不做
- 否则,早点归还号码
def findMissingNo(arr, s):
for num in s: #loop through each element in the set
for num2 in arr: ##loop through each element in the array O(n)
if (num == num2): #if the number in the set is in the array, break
break
print (num)
return num #if the number in the set is not in the array, early return the number
return -1 #return -1 if there is no missing element
s1 = {1,4,5}
arr1 = [1,4]
findMissingNo(arr1, s1)
【问题讨论】:
-
你不能只做
s1-set(arr1)吗?两组上的-执行difference