查找重复的元素--三种方法

it2025-05-17  14

#方法一:

def repeatNtimes(A): import collections A_dict = collections.Counter(A) A_tuple = sorted(A_dict.items(),key=lambda x:x[1],reverse=True) return A_tuple[0][0] print(repeatNtimes([1,2,3,3])) print(repeatNtimes([2,1,2,5,3,2])) print(repeatNtimes([5,1,5,2,5,3,5,4]))

#方法二:

def repeatNtimes(A): import collections A_dict = collections.Counter(A) return max(A_dict,key=A_dict.get) print(repeatNtimes([1,2,3,3])) print(repeatNtimes([2,1,2,5,3,2])) print(repeatNtimes([5,1,5,2,5,3,5,4]))

#方法三:

def repeatNtimes(A): d={} for a in A: if a not in d: d[a]=1 else: return a print(repeatNtimes([1,2,3,3])) print(repeatNtimes([2,1,2,5,3,2])) print(repeatNtimes([5,1,5,2,5,3,5,4]))
最新回复(0)