繁体   English   中英

是否有一种 O(n) 方法可以在不使用计数器的情况下找到列表中重复次数最多的项目

[英]Is there a O(n) way to find the most repeated item in list without using counter

我需要一个 O(n) 的解决方案来查找列表中重复次数最多的元素。 如果 2 个或更多数字重复相同的时间,则返回最小的数字。

from collections import Counter
 
def most_frequent(n):
    count_occurence = Counter(n)
    return count_occurence.most_common(1)[0][0]

input = [2,4,4,5,2,3,3,4,5,6,6,6,1]

输出应该是 4 这应该给出 3 的计数

您可以使用maxgroupby

from itertools import groupby

def most_frequent(li):
    maxes=[]
    for k,g in groupby(sorted(li)):
        maxes.append((len(list(g)), -k))
        
    return -max(maxes)[1]

或者使用 dict 作为计数器:

def most_frequent(li):
    cnt={}
    for e in li:
        cnt[-e]=cnt.get(-e, 0)+1
    
    return -max(cnt.items(), key=lambda t: (t[1],t[0]))[0]

或者,如果您的数据运行的数字相似,则无需 O(n log n) 排序步骤,您可以组合这两种方法:

def most_frequent(li):
    cnt={}
    for k,g in groupby(li):
        cnt[-k]=cnt.get(-k,0)+len(list(g))
        
    return -max(cnt.items(), key=lambda t: (t[1],t[0]))[0]

并且很可能在理解上使用max比使用 lambda 更快:

def most_frequent(li):
    cnt={}
    for k,g in groupby(li):
        cnt[-k]=cnt.get(-k,0)+len(list(g))
                
    return -max(((y,x) for x,y in cnt.items()))[1]

在所有情况下,您都在构建一个(-element_in_list, count_of_that_element)元组:

cnt=[(-2, 2), (-4, 3), (-5, 2), (-3, 2), (-6, 3), (-1, 1)]

然后,您可以通过对关键函数的理解来反转元组来获取该max 你的答案是-element_in_list因为它被否定了max

暂无
暂无

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

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