[Leetcode] Top K Frequent Elements
程序员文章站
2022-03-23 12:30:06
...
手动再见,这个问题困扰我好久!
为什么输出的list一直多一个元素啊!
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
bucket = [list() for i in range(len(nums)+1)] #array of list
freq = {}
#account the frequencies
for n in nums:
freq[n] = freq.get(n,0)+1
#set the bucket
for k,v in freq.items():
bucket[v].append(k)
res = []
print(bucket)
for i in range(len(bucket)-1,-1,-1):
print(len(res))
if len(res) >= k:
return res
elif len(bucket[i])>0:
res.extend(bucket[i])
print(res)
return res
这真的是什么2B结果。。。
——————————
我终于发现了!!
k是函数参数,可是我却把它作为字典键值加入了迭代器,字典迭代完之后k就变掉了!!!
啊啊啊!!
推荐阅读
-
LeetCode刷题笔记(Top K Frequent Elements)
-
TOP K frequent-elements
-
LeetCode 692. Top K Frequent Words
-
Leetcode 692. Top K Frequent Words
-
692. Top K Frequent Words
-
LeetCode 347: 前 K 个高频元素 Top K Frequent Elements
-
Top K Frequent Elements
-
(Java)leetcode-347 Top K Frequent Elements
-
[Leetcode] Top K Frequent Elements
-
LeetCode 347. Top K Frequent Elements