python - 使用 O(n) 时间和 O(1) 空间查找最频繁出现的元素

标签 python algorithm

我想在 O(n) 时间和 O(1) 空间中找到列表中最常出现的元素。

第一个解决方案

from collections import Counter
def max_repetitions(elements):
    return max([v for k, v in Counter(elements).items() if v > 1])

空间复杂度为O(n)。我不确定时间复杂度。是O(nlogn)还是O(n)

第二种解决方案

def max_repetitions(elements):
counter = 0
for k, v in Counter(elements).items():
    if v > 1 and counter < v:
        counter = k
return counter

该解决方案的时间复杂度是多少?是O(nlogn)还是O(n)

还有其他办法吗?

最佳答案

在这样的简单情况下:要获得时间复杂度,请尝试回答您迭代序列中的元素的次数。

由于您在 collections 模块中使用 Counter 类,这也会影响复杂性,但我们假设它的复杂度为 O(n)。

您要做的唯一其他工作是再次迭代列表,也是 O(n)。时间复杂度为 O(n),因为它随着元素 n 的数量线性增长。

关于python - 使用 O(n) 时间和 O(1) 空间查找最频繁出现的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31996534/

相关文章:

python - 如何在 python 中将变量从文本 "1m"更改为 "1000000"

python - 到盒子编号的 X-Y 坐标

c++ - 检查2个字符串中是否有公共(public)子字符串c++

algorithm - 有多少二叉树可能满足给定的前序和后序遍历?

algorithm - 创建建议词算法

python - 鉴于两个项目不能在同一个列表中,如何获得列表的所有组合?

python - python中模式匹配时间格式的正则表达式

python - 根据分配方法返回不同输出的字符串的身份检查

python - 如何在 pandas 中剪切连续变量

algorithm - 3 logn 和 2logn 的复杂度一样吗?