Leetcode转K个频繁元素

问题描述 投票:0回答:1

我正在尝试解决问题(给定一个整数数组 nums 和一个整数 k,返回 k 个最常见的元素。您可以按任何顺序返回答案。) 通过创建一个哈希图,其中键是list

nums
并且该值的对是该项目出现在列表中的时间量。我循环遍历列表,然后有一个 if 语句检查该项目是否已经是字典中的键,如果是,则将其值加 1,如果不是,则将其添加为键并为其赋予值1. 当我运行列表
nums = [1, 1, 1, 2, 2, 3]
的代码时,输出完全错误。这是预期的输出
{1: 3, 2: 2, 3: 1}
而我收到的是
{1: 5, 2: 1}

这是我的代码:

nums = [1,1,1,2,2,3]
iterations = {}

for x in nums:
    if nums[x] in iterations:
        iterations[nums[x]] += 1
    else:
        iterations[nums[x]] = 1

print(iterations)
python hashmap
1个回答
0
投票

代码的更正版本

 nums = [1, 1, 1, 2, 2, 3]
 iterations = {}
  
 for x in nums:
     if x in iterations:
         iterations[x] += 1
     else:
         iterations[x] = 1

 print(iterations)
© www.soinside.com 2019 - 2024. All rights reserved.