Algorithm/1일 1코테
[🥰 leetcode] 692. Top K Frequent Words
대인보우
2022. 10. 19. 12:51
반응형
https://leetcode.com/problems/top-k-frequent-words/
리스트 안에 가장 많이 존재하는 단어순 && 갯수가 같은 경우엔 사전순 정렬을 기준으로 k개를 뽑아내는 문제
나의 풀이
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# 중복없는 set 생성
w_set = set(words)
count_list = []
# set에서 하나씩 뽑아내서 리스트 안의 count 계산 후 count_list에 넣는다.
for word in w_set:
count = words.count(word)
count_list.append((count,word))
# count 리스트에서 count 높은 순 => 사전순으로 정렬
count_list.sort(key=lambda x: (-x[0], x[1]))
# k개만큼 뽑아준다.
return [count_list[i][1] for i in range(k)]
다른 사람 풀이
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
# 글자수 세기
counts = collections.Counter(words)
# 단어와 카운트 (1, 'i') 이런식으로 구성
# -를 붙여줌으로써 역순 출력
heap = [(-count, word) for word, count in counts.items()]
# heap으로 작은것부터 순서 정렬 (-를 붙여줘서 사실상 큰 순서대로 정렬됨)
heapq.heapify(heap)
# k 개수만큼 뽑기
return [heapq.heappop(heap)[1] for _ in range(k)]
반응형