Skip to content

Commit bd4beca

Browse files
committed
solution: top-k-frequent-elements
1 parent 9c694e9 commit bd4beca

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import heapq
2+
3+
4+
class Solution:
5+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
# ํ•˜๋‚˜์”ฉ ์ „๋ถ€ ๋Œ๋ฉด์„œ ๋นˆ๋„์ˆ˜ ์ €์žฅ, k๊ฐœ๋งŒํผ๋งŒ
7+
# cnt ํ•จ์ˆ˜๋ฅผ ์จ์„œ ๋น„๊ตํ›„ ์ €์žฅ -> ๋” ๋งŽ์€ ๋ฐ˜๋ณต?
8+
# ์ผ๋‹จ ํ•œ๋ฒˆ์€ ๋‹ค ๋Œ์•„์•ผํ•จ. ๊ฐ€์žฅ ์ ๊ฒŒ ๋Œ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•?
9+
# ์ „์ฒด ์ˆœ์ฐจ ๋น„๊ต?
10+
11+
table = {}
12+
13+
for i in range(len(nums)):
14+
table[nums[i]] = table.get(nums[i], 0) + 1
15+
16+
topk = heapq.nlargest(k, table, key=table.get)
17+
return topk

0 commit comments

Comments
ย (0)