LeetCode 347. Top K Frequent Elements

개발공부를해보자·2025년 1월 19일

LeetCode

목록 보기
31/95

파이썬 알고리즘 인터뷰 문제 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번 나온 것을 횟수와 함께 튜플로 받은 후 이를 리스트 컴프리헨션을 이용하여 숫자만 모아주었다.

다른 풀이1


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을 좋아하는 것 같다.

다른 풀이2

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = collections.Counter(nums)
        return list(zip(*count.most_common(k)))[0]
  • 나의 풀이와 마찬가지로 Countermost_common을 이용하는데 *(unpacking)과 zip을 이용하였다.
  • 리턴 값이 list가 아닌 tuple인데 간단히 바꾸어줘도 되고, 이 문제에서는 정답으로 처리된다.

zip*(unpacking)에 대한 자세한 내용
https://velog.io/@coding_study/zip과-을-이용한-언패킹unpacking

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글