我想找到最频繁发生的元素的列表,O(n)
时间和空间O(1)
最频繁出现的元素。查找具有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)
?
有没有其他办法?
这两个看起来像O(n)的空间,在最坏情况下的复杂性。如果你的初始列表等于'range(1000)',那么你的计数器将占用1000个插槽。 (是的,它仍然被认为占用空间,即使你从来没有给它一个变量名) – Kevin
他们都应该有时间为O(n)的复杂性。 –