거누의 개발노트
파이썬 알고리즘 인터뷰 - 상위 K 빈도 요소 ( * ) 본문
반응형
문제
상위 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라는 함수가 있는걸 알게되었다.
최빈값을 찾아주는 함수이다.
반응형
'코딩테스트' 카테고리의 다른 글
파이썬 알고리즘 인터뷰 - 전화 번호 문자 조합 (0) | 2022.05.19 |
---|---|
[파이썬] 백준 - 수 찾기 - 1920 (0) | 2022.05.18 |
파이썬 알고리즘 인터뷰 - 중복 문자 없는 가장 긴 부분 문자열 ( * ) (0) | 2022.05.18 |
파이썬 알고리즘 인터뷰 - 보석과 돌 (0) | 2022.05.18 |
[파이썬] 백준 - 프린터 큐 - 1966 ( * ) (0) | 2022.05.17 |
Comments