【问题标题】:Programming Challenge Code taking too much time编程挑战代码花费太多时间
【发布时间】:2016-04-29 11:37:08
【问题描述】:

我为this problem.写了以下代码

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,但它产生了一个 TLE,我相信这是因为in 语句是O(n)。因此,我编写了这段代码,其所需的步骤大致等于两个列表的长度之和。但这也产生了 TLE。那么,我应该对我的代码进行哪些更改。是否有一些特别的部分需要花费大量的时间?

谢谢。

【问题讨论】:

  • 由于代码正在运行,也许这更适合Code Review

标签: python algorithm performance python-3.x


【解决方案1】:

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

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

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

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

【讨论】:

  • 集合比地图更好,因为只需要包含检查。
  • 但是set 删除了重复项。我们必须计算重复项。
  • @Some Name 仅使用 prof 数据设置,正如我所写的。因此,您将计算所有学生数据,包括重复数据。而且你不应该关心 prof 列表中的重复项,他们不会打扰。
  • @MBo 抱歉,请查看其他答案。在那里,他用他们俩做了一套。这是为了另一个答案。
  • 是的,我看到了那个答案。但在我的回答中,我建议根据教授集检查每个学生的价值。
【解决方案2】:

由于问题基本上是找到两组整数的交集,因此当假设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))

【讨论】:

  • 但是set 删除了重复项。我们必须计算重复项。
猜你喜欢
  • 2014-01-13
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 2012-04-02
相关资源
最近更新 更多