在随机整数列表中,整数在列表中重复,如何从列表中打印出根本不重复的整数?
我试图通过编写以下程序来解决这个问题:
K = int(input())
room_list = list(input().split())
room_set = set(room_list)
for i in room_set:
count = room_list.count(i)
if count == 1:
i = int(i)
print(i)
break
K 是列表中元素的数量。
当我尝试运行上述程序时,它在元素较少的情况下运行良好,但是,当使用具有(比如 825)个元素的列表对其进行测试时,程序超时。
请帮我优化上面的代码。
最佳答案
列表中重复次数为 1 的元素将是您的答案。
from collections import Counter
a = [1,1,1,2,2,3,4,5,5]
c = Counter(a) # O(n)
x = [key for key, val in c.items() if val == 1]
print(x)
输出:
[3,4]
Counter class通过遍历列表一次来创建元素和重复项的字典,这需要时间 O(n) 并且每个元素的访问需要 O(1) 时间。
每次在列表上调用时,列表的计数函数都会迭代。在您的情况下需要 O(n^2) 时间。
关于 python 3 : Integer not repeated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033198/