【发布时间】:2021-06-22 07:52:04
【问题描述】:
编写一个函数,该函数接受一个整数数组并返回一个新数组,其中包含最常出现的两个整数。
函数当前接受数组输入并将其转换为字典对象。
[3,3,1,2,1,1,4,4,4,4] ==> {3: 2, 1: 3, 2: 1, 4: 4}
如何按值对字典进行排序并在新数组中返回两个最高值的键?前任。 [4,1]
def majority_element_top_two(arr):
int_dict = {}
for i in range(len(arr)):
if arr[i] not in int_dict:
int_dict[arr[i]] = 1
else:
int_dict[arr[i]] += 1
return int_dict
print(majority_element_top_two([3,3,1,2,1,1,4,4,4,4]))
【问题讨论】:
-
按值排序字典 => 这里有很多匹配项,返回两个最高值的键 => 反转映射并获取键
标签: python arrays sorting dictionary