Skip to content

347. Top K Frequent Elements#11

Open
TrsmYsk wants to merge 1 commit intomainfrom
347.-Top-K-Frequent-Elements
Open

347. Top K Frequent Elements#11
TrsmYsk wants to merge 1 commit intomainfrom
347.-Top-K-Frequent-Elements

Conversation

@TrsmYsk
Copy link
Owner

@TrsmYsk TrsmYsk commented Feb 1, 2026

Add detailed explanation and implementation for the Top K Frequent Elements problem, including various approaches such as using collections.Counter, heapq, and bucket sort.
Comment on lines +57 to +59
frequency = {}
for number in nums:
frequency[number] = frequency.get(number, 0) + 1
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[fyi]
defaultdict を使うとさらにシンプルに書けます。

Suggested change
frequency = {}
for number in nums:
frequency[number] = frequency.get(number, 0) + 1
frequency = defaultdict(int)
for number in nums:
frequency[number] += 1

Comment on lines +60 to +62
top_k_items = sorted(frequency.items(), key=itemgetter(1), reverse=True)[:k]
top_k_numbers = list(dict(top_k_items))
return top_k_numbers
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こちらも、もうちょっとシンプルに書けます。

Suggested change
top_k_items = sorted(frequency.items(), key=itemgetter(1), reverse=True)[:k]
top_k_numbers = list(dict(top_k_items))
return top_k_numbers
top_k_numbers = sorted(frequency, key=frequency.get, reverse=True)[:k]
return top_k_numbers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants