파이썬 알고리즘 인터뷰 문제 31번(리트코드 347번) Top K Frequent Elements
https://leetcode.com/problems/top-k-frequent-elements/
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = collections.Counter(nums)
return [x for (x, y) in count.most_common(k)]
Counter를 이용하여 각 숫자 출현 횟수를 세어주고 most_common(k)를 이용하여 상위 k번 나온 것을 횟수와 함께 튜플로 받은 후 이를 리스트 컴프리헨션을 이용하여 숫자만 모아주었다.
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = collections.Counter(nums)
heap = []
result = []
for num in freq:
heapq.heappush(heap,(-freq[num], num))
for _ in range(k):
result.append(heapq.heappop(heap)[1])
return result
heap을 이용한 풀이. 이 책 저자는 heap을 좋아하는 것 같다.class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = collections.Counter(nums)
return list(zip(*count.most_common(k)))[0]
Counter와 most_common을 이용하는데 *(unpacking)과 zip을 이용하였다.list가 아닌 tuple인데 간단히 바꾸어줘도 되고, 이 문제에서는 정답으로 처리된다.
zip과*(unpacking)에 대한 자세한 내용
https://velog.io/@coding_study/zip과-을-이용한-언패킹unpacking