在这段代码中,我试图在字符串列表中找到最常见的名称,以便程序在 O(nlogn) 中运行。我认识到这可以用字典在 O(n) 中完成。有什么明显的方法可以使这段代码更好吗?
def mostCommonName(L):
#in these two cases I'm making sure that if L has only one element in it
#or if it's empty that the correct result is returned before the loop
if len(L) == 1:
return L[0]
if len(L) == 0:
return None
#this automatically makes it nlogn
newL = sorted(L)
maxCount = 0
currCount = 1
maxName = set()
currName = newL[0]
for name in range(1,len(newL)):
if newL[name] == currName:
currCount += 1
else:
if currCount >= maxCount:
maxCount = currCount
currCount = 1
maxName.add(currName)
currName = newL[name]
else:
currCount = 1
currName = newL[name]
if newL.count(newL[-1]) == maxCount:
maxName.add(newL[-1])
if len(maxName) == 1:
return maxName.pop()
return maxName
扬帆大鱼
倚天杖
相关分类