코딩테스트
파이썬 알고리즘 인터뷰 - 상위 K 빈도 요소 ( * )
Gogozzi
2022. 5. 18. 15:22
반응형
문제
상위 K번 이상 등장하는 요소를 추출하라.
입력
num = [1,1,1,2,2,3]
k = 2
출력
[1,2]
작성한 코드
def topKFrequent1(nums: List[int], k: int) -> List[int]:
count = list(collections.Counter(nums).most_common(k)) # k 이상의 최빈값
rtn = []
for i in range(len(count)):
rtn.append(count[i][0])
return rtn
파이썬다운 방식
def topKFrequent2(nums: List[int], k: int) -> List[int]:
return list(zip(*collections.Counter(nums).most_common(k)))[0]
리코드에서 확인
https://leetcode.com/problems/top-k-frequent-elements/submissions/
Top K Frequent Elements - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
회고
collections.Counter에서 뽑는거 까지는 생각했는데, most_common라는 함수가 있는걸 알게되었다.
최빈값을 찾아주는 함수이다.
반응형