Skip to content

Commit f4cafbc

Browse files
committed
Top K Frequent Elements solution
1 parent 7755c5d commit f4cafbc

1 file changed

Lines changed: 32 additions & 8 deletions

File tree

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,36 @@
1+
2+
# 6๊ธฐ
3+
# class Solution:
4+
# # dictionary use
5+
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
# result = {} # key: ์›์†Œ, value: ๋“ฑ์žฅ ํšŸ์ˆ˜
7+
# for n in nums:
8+
# if n in result:
9+
# result[n] = result[n] + 1
10+
# else:
11+
# result[n] = 1
12+
13+
# # ๊ฐ€์žฅ ์ž์ฃผ ๋“ฑ์žฅํ•œ ์›์†Œ k๊ฐœ ๋ฐ˜ํ™˜
14+
# return sorted(result.keys(), key=lambda x: result[x], reverse=True)[:k]
15+
16+
# 7๊ธฐ
117
class Solution:
2-
# dictionary use
318
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
4-
result = {} # key: ์›์†Œ, value: ๋“ฑ์žฅ ํšŸ์ˆ˜
5-
for n in nums:
6-
if n in result:
7-
result[n] = result[n] + 1
19+
# 1. Count frequency of each number
20+
freq = {}
21+
22+
for num in nums:
23+
if num not in freq:
24+
freq[num] = 1
825
else:
9-
result[n] = 1
26+
freq[num] += 1
27+
28+
# 2. Sort by frequency in descending order
29+
sorted_items = sorted(freq.items(), key=lambda item: item[1], reverse=True)
30+
31+
# 3. Take the first k elements
32+
result = []
33+
for i in range(k):
34+
result.append(sorted_items[i][0])
1035

11-
# ๊ฐ€์žฅ ์ž์ฃผ ๋“ฑ์žฅํ•œ ์›์†Œ k๊ฐœ ๋ฐ˜ํ™˜
12-
return sorted(result.keys(), key=lambda x: result[x], reverse=True)[:k]
36+
return result

0 commit comments

Comments
ย (0)