π 347. TOP K Frequent Elements
μμ k λ² μ΄μ λ±μ₯νλ μμλ₯Ό μΆλ ₯
Input : nums = [1,1,1,2,2,3] , k = 2
def solution(nums, k):
ans = collections.defaultdict(int)
result = []
for char in nums:
ans[char] += 1
for char in ans:
if ans[char] >= k:
result.append(char)
return result
νμ΄ μλλ λ€μκ³Ό κ°λ€.
λ¬Έμ λ₯Ό μ λͺ» μ΄ν΄νλ€... μ£Όμ΄μ§ k, μ¦ 2 μ΄μ λ±μ₯νλ μλ₯Ό λ°°μ΄μ λ΄μ μΆλ ₯νλ©΄ λλκ±΄μ§ μμλλ°, μμ λ¬Έμ λ₯Ό μ€λͺ ν κ²κ³Ό κ°μ΄ λ±μ₯ν μμ(k)λ₯Ό κΈ°μ€μΌλ‘ μκ°νμ΄μΌ νλ€.
def solution(nums, k):
ans = collections.Counter(nums)
d = []
result = ans.most_common(k)
for idx, freq in result:
d.append(idx)
return d
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
'''
μλ most_common μ λλ¬ λ€μ΄κ° μ€λͺ
μ΄λ€. μ€λͺ
κ³Ό κ°μ΄ most_common μ λ§€κ°λ³μλ§νΌ λ±μ₯ν κ°λ€μ μ μ₯νλ€.
.
.
μ½λ© ν
μ€νΈλ λ³΄ν΅ idle μ μ 곡νμ§ μλλ€. νμ΄μ¬μ λ§μ λΌμ΄λΈλ¬λ¦¬λ₯Ό μ 곡νμ§λ§ idle μ΄ μμ λλ νΈνκ³ μμ°μ€λ½κ² μ¬μ©ν μ μλλ‘ λ§μ΄ μ°μ΅νμ.