繁体   English   中英

编写挑战代码需要太多时间

[英]Programming Challenge Code taking too much time

我针对此问题编写了以下代码

prof = sorted([int(input()) for x in range(int(input()))])
student = sorted([int(input()) for x in range(int(input()))])

prof_dates = len(prof)
stud_dates = len(student)

amount = 0

prof_index = 0
stud_index = 0

while stud_index < stud_dates and prof_index < prof_dates:
    if student[stud_index] == prof[prof_index]:
        amount += 1
        stud_index += 1

    elif student[stud_index] > prof[prof_index]:
        prof_index += 1

    elif student[stud_index] < prof[prof_index]:
        stud_index += 1


print(amount)

但是代码产生了超过时限的错误。 早些时候,我尝试对in中的每个项目使用in ,但是它产生了TLE,我相信这是因为in语句是O(n) 因此,我编写了这段代码,所需步骤大致等于两个列表的长度之和。 但这也会产生一个TLE。 因此,我应该在代码中进行哪些更改。 是否有某些特定的零件会花费大量时间?

谢谢。

您正在使用排序+合并。 这需要O(NlogN + MlogM + N + M)时间复杂度。

但是您可以将教授数据放入一个set ,检查每个学生的年值(从未排序的列表中),并获得O(M + N)复杂度(平均)。

注意,这种方法消除了学生列表排序的冗长操作。

另外:python具有内置集。 对于没有此类规定的语言,教授的名单已经排序,因此您可以每年使用二进制搜索。 复杂度为O(NlogM)

因为问题基本上是找到两组整数的交集,所以以下代码在假定O(1)可以进行字典访问的情况下解决了O(M + N)的问题。

prof = set([int(input()) for x in range(int(input()))])
student = set([int(input()) for x in range(int(input()))])

equals_dates = len(prof.intersection(student))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM