def find_most_frequent(arr):
# 统计每个整数出现的次数,保存在字典中
num_count = {}
for num in arr:
if num in num_count:
num_count[num] += 1
else:
num_count[num] = 1
# 找到出现次数最多的两个整数
# 初始化为数组中的前两个整数
top_two = [arr[0], arr[1]]
top_one = arr[0]
for num in num_count:
count = num_count[num]
if count > num_count[top_one]:
top_two = [top_one, num]
top_one = num
elif count > num_count[top_two[0]]:
top_two[1] = top_two[0]
top_two[0] = num
elif count > num_count[top_two[1]]:
top_two[1] = num
# 返回前两个整数
return top_two
以上代码通过遍历数组,利用字典统计每个整数出现的次数,再根据出现的次数排序找到出现频率最高的两个整数。返回这两个整数组成的新数组。