Given an integer array nums and an integer k, return the k most frequent elements within the array.
The test cases are generated such that the answer is always unique.
You may return the output in any order.
Example 1:
Input: nums = [1,2,2,3,3,3], k = 2
Output: [2,3] Example 2:
Input: nums = [7,7], k = 1
Output: [7]
In [25]:
def topKFrequent(nums,k):
numdict={}
for num in nums:
if num in numdict:
numdict[num]+=1
else:
numdict[num]=1
freqlist=[]
for i in range(len(nums)+1):
freqlist.append([])
for key, val in numdict.items():
freqlist[val].append(key)
result=[]
for i in range(len(freqlist)-1,0,-1):
for num in freqlist[i]:
result.append(num)
if len(result)==k:
return result
In [26]:
topKFrequent([1,2,2,3,3,3],2)
Out[26]:
[3, 2]
In [27]:
{1:2,3:4}.items()
Out[27]:
dict_items([(1, 2), (3, 4)])
In [28]:
freqlist=[]
for i in range(5):
freqlist.append([])
print(freqlist)
[[], [], [], [], []]