我尝试执行的程序有以下问题陈述:
The program must accept N integers containing integers from 1 to N with duplicates in any order. The program must print the missing integers from 1 to N among the given integers in ascending order as the output.
例子:
Input: 5
2 5 5 1 1
Output: 3 4
Explanation: The integers 3 and 4 are missing in the 5 integers 2 5 5 1 1. Hence 3 and 4 are printed as the output
我的代码:
def modusoperandi(n, t):
if str(n) not in t:
yield n
n = int(input())
t = tuple(sr for sr in input().split())
for i in range(1,n+1):
for j in modusoperandi(i,t):
print(j,end=' ')
但是,我的代码未能通过所有测试用例,因为执行具有大量输入的测试用例需要花费大量时间[超过 500 毫秒,这是时间限制]。
我尝试使用 timeit 方法计算执行时间。奇怪的是,当元组中的元素数量增加时,给定 N 的执行时间也会增加。我更喜欢元组而不是列表,因为它应该更有效率。
请您参考如下方法:
您需要将现有数字转换为integers,然后将它们放入set;集合对于确定给定值是否为成员非常有效。
n = int(input())
extant = set(int(n) for n in input().split())
for i in range(1, n + 1):
if i not in extant:
print(i, end=" ")
