본문 바로가기
Algorithm/LEET CODE ( 파이썬 알고리즘 인터뷰)

[LEET CODE] 347. Top K Frequent Elements( zip 함수, * (아스테리스크))

by newnu 2021. 4. 5.
반응형

# Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

 

 

Constraints:

  • 1 <= nums.legth <= 105
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

 

# My Answer

import collections
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        result =[]
        n = collections.Counter(nums).most_common(k)
        for i in n:
            result.append(i[0])
        return result

 

# Solution 1 - Counter를 이용한 음수 순 추출

import collections
import heapq

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freqs = collections.Counter(nums)
        freqs_heap = []
        # 힙에 음수로 삽입
        for f in freqs:
            heapq.heappush(freqs_heap, (-freqs[f], f))

        topk = list()
        # k번 만큼 추출, 민 힙 이므로 가장 작은 음수 순으로 추출
        for _ in range(k):
            topk.append(heapq.heappop(freqs_heap)[1])

        return topk

힙은 키 순서대로 정렬되므로 빈도수를 키로 선택

파이썬 heapq 모듈은 최소힙만 지원하기 때문에 빈도수를 음수로 변환하여 저장

 

# Solution 2 - 파이썬다운 방식

import collections


class Solution:
    def topKFrequent(self, nums, k):
        return list(zip(*collections.Counter(nums).most_common(k)))[0]

zip() : 2개 이상의 시권스를 짧은 길이를 기준으로 일대일 대응하는 새로운 튜플 시퀀스 생성

a=[ 1,2,3,4,5]

b=[6,7,8,9]

list(zip(a,b)) = [ (1,6), (2,7), (3,8), (4,9) ]

 

* (아스테리스크) - 파이썬에서는 Unpack

시퀀스를 언팩킹하는 연산자

*로 언팩킹 해줘야 튜플을 풀수 있다  

* (1개 ) : 튜플, 리스트 등의 시퀀스 언팩킹

**(2개) : 키, 값 페어 언패킹

반응형