nums = [1,1,1,2,2,3],
k = 2
return [1,2]
nums = [1]
k = 1
return [1]
from collections import Counter
def top_k(nums, k):
cnt = Counter(nums)
top = cnt.most_common()
result = []
for n in range(k):
result.append(top[n][0])
return result
class collections.Counter([iterable-or-mapping])
- 만약 [1,1,1,2,2,3] 리스트를 Counter 에 인자로 주고 리턴 값을 받는다면,
Counter({1: 3, 2: 2, 3: 1}) 리턴- most_common 메서드를 사용하면
[(1, 3), (2, 2), (3, 1)] 리턴
from collections import Counter
def top_k(nums, k):
cnt = Counter(nums)
top = cnt.most_common(k)
return list(map(lambda x: x[0], top))
def top_k(nums, k):
count = {}
for n in nums:
count[n] = count.get(n, 0) + 1
bucket = [[] for _ in range(len(nums)+1)]
for n, freq in count.items():
bucket[freq].append(n)
ret = []
for n_list in bucket[::-1]:
if n_list:
ret.extend(n_list)
if len(ret) == k:
return ret
(솔루션 분석 중..)