【发布时间】:2021-05-10 03:46:13
【问题描述】:
谁能解释为什么我的黑客等级示例代码超时。我对基于处理时间的代码效率的整体概念不熟悉。该代码似乎适用于小型数据集,但是一旦我开始使用大型数据集测试用例,它就会超时。我提供了对该方法及其上下文目的的简要说明。但是,如果您发现我正在使用的函数可能会消耗大量运行时,那么如果您能提供任何提示,那就太好了。
完成下面的候鸟功能。 参数: arr:通过索引看到的鸟类种类的数组。 例如。 arr = [Type1 = 1, Type2 = 4, Type3 = 4, Type4 = 4, Type5 = 5, Type6 = 3] 返回目击模式的最低类型。在这种情况下,4 次目击是 模式。 Type2 是具有模式的最低类型。所以返回整数 2。
def migratoryBirds(arr):
# list of counts of occurrences of birds types with the same
# number of sightings
bird_count_mode = []
for i in range(1, len(arr) + 1):
occurr_count = arr.count(i)
bird_count_mode.append(occurr_count)
most_common_count = max(bird_count_mode)
common_count_index = bird_count_mode.index(most_common_count) + 1
# Find the first occurrence of that common_count_index in arr
# lowest_type_bird = arr.index(common_count_index) + 1
# Expect Input: [1,4,4,4,5,3]
# Expect Output: [1 0 1 3 1 0], 3, 4
return bird_count_mode, most_common_count, common_count_index
附:感谢您的编辑克里斯查理。我只是尝试同时编辑它
【问题讨论】:
-
这是完全错误的:
occurr_count = arr.count(i)。i是一个列表索引,但count()用于计算列表元素。应该是arr.count(arr[i]) -
即使你做得对,它也是一个 O(n^2) 算法。您可以使用字典计算 O(n) 中的元素。还有一个库函数
collections.Counter()可以为您完成这项工作。 -
@Barmar 所以我认为 collections.Counter() 更有效?抱歉,我不熟悉 O(n^2) 与 O(n) 的概念,但我现在正在研究它。
-
对
arr.count(i)的每次调用都是 O(n),你执行它们 n 次,使得算法 O(n^2)。 -
collections.Counter()大概使用类似for i in list: counter[i]+=1