Skip to content

Commit dd9d024

Browse files
committed
top-k-frequent-elements sol (py)
1 parent e4c8c55 commit dd9d024

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed
Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
1-
# 가장 자주 등장한 상위 K개의 문자 배열 반환
2-
# O(n log n) time, O(n) space
1+
"""
2+
https://leetcode.com/problems/top-k-frequent-elements/
3+
4+
Given an integer array nums and an integer k, return the k most frequent elements.
5+
You may return the answer in any order.
6+
7+
TC: O(n log n)
8+
SC: O(n)
9+
"""
310

411
from collections import defaultdict
12+
from typing import List
513

614
class Solution:
715
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
8-
numdict = defaultdict(int);
16+
numdict = defaultdict(int)
917

1018
for num in nums:
1119
numdict[num] += 1
@@ -15,3 +23,14 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
1523
keys = list(sort_dict)
1624

1725
return keys[:k]
26+
27+
# heapq 풀이
28+
from collections import Counter
29+
import heapq
30+
31+
class Solution:
32+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
33+
counter = Counter(nums)
34+
return heapq.nlargest(k, counter.keys(), key=counter.get)
35+
36+

0 commit comments

Comments
 (0)