【问题标题】:Write a function which accepts an array of integers and returns a new array the two integers that appear most frequently编写一个函数,该函数接受一个整数数组并返回一个新数组,其中包含最常出现的两个整数
【发布时间】: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]))

image

【问题讨论】:

  • 按值排序字典 => 这里有很多匹配项,返回两个最高值的键 => 反转映射并获取键

标签: python arrays sorting dictionary


【解决方案1】:

代码:

def majority_element_top_two(arr):
    int_dict = {}    
    for i in arr:
        if i not in int_dict:  
            int_dict[i] = 1
        else:                       
            int_dict[i] += 1     
    return list({k: v for k, v in sorted(int_dict.items(), key=lambda item: item[1],reverse=True)}.keys())[:2]

print(majority_element_top_two([3,3,1,2,1,1,4,4,4,4]))

结果:

[4, 1]

【讨论】:

  • 解决方案非常完美。谢谢你。只是好奇,你能进一步解释一下return语句吗?
  • 按值排序字典,然后得到排序后的字典的keys(),改成list,使用[:2]切片函数得到最高值。 @Dominic Holder
猜你喜欢
  • 2021-01-14
  • 2011-06-10
  • 2016-04-11
  • 1970-01-01
  • 2019-01-19
  • 2021-03-30
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多