일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 니트코드
- dfs
- 생성형AI
- Python
- 알고리즘
- 파이썬기초100제
- gcp
- 자연어처리
- Greedy
- 코드업
- 릿코드
- LeetCode
- array
- SQL
- GenerativeAI
- codeup
- 투포인터
- heap
- Stack
- 슬라이딩윈도우
- nlp
- GenAI
- Python3
- slidingwindow
- 파이썬알고리즘
- 리트코드
- stratascratch
- 파이썬
- sql코테
- two-pointer
Archives
- Today
- Total
Tech for good
[Neetcode/Greedy, Hash Map, Sort] Top K Frequent Elements 본문
IT/Computer Science
[Neetcode/Greedy, Hash Map, Sort] Top K Frequent Elements
Diana Kang 2025. 6. 24. 11:31https://neetcode.io/problems/top-k-elements-in-list?list=neetcode150
NeetCode
neetcode.io
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
m ={}
ans =[]
for i in nums:
if i in m:
m[i]+=1
else: m[i] = 1
l = sorted(m.keys(), key=lambda num: m[num], reverse=True)
for u in range(k):
ans.append(l[u])
return ans
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq_map = {}
for num in nums:
freq_map[num] = freq_map.get(num, 0) + 1
sorted_keys = sorted(freq_map.keys(), key=lambda x: freq_map[x], reverse=True)
return sorted_keys[:k]
freq_map[num] = freq_map.get(num, 0) + 1
Count how many times each number appears:
- If num already exists in freq_map, get its count and add 1.
- If not, get() returns 0, and you set it to 1.
We add +1 to keep track of how many times each number appears.
.get(num, 0) ensures the first time we see the number, we start from 0.
✅ Example:
nums = [1, 2, 2, 3, 3, 3]
# freq_map becomes: {1: 1, 2: 2, 3: 3}
sorted_keys = sorted(freq_map.keys(), key=lambda x: freq_map[x], reverse=True)
- Sort the keys (unique numbers) by their frequency, from highest to lowest:
- lambda x: freq_map[x] sorts by each number’s frequency.
- reverse=True means most frequent comes first.
✅ Example:
sorted_keys = [3, 2, 1] # if freq_map = {1:1, 2:2, 3:3}
return sorted_keys[:k]
- Return the first k elements from the sorted list.
- These are the k most frequent numbers.
✅ Example:
k = 2
# return [3, 2]
🔍 What is .get() in Python dictionaries?
.get() is a dictionary method that allows you to safely retrieve a value for a given key, with an optional default value if the key doesn't exist.
✅ Syntax:
dictionary.get(key, default_value)
- key: the key you’re trying to access.
- default_value (optional): the value to return if the key is not found.
- If omitted, None is returned by default.
📌Example:
m = {'a': 2, 'b': 5}
print(m.get('a')) # ➜ 2
print(m.get('c')) # ➜ None (since 'c' is not in the dictionary)
print(m.get('c', 0)) # ➜ 0 (returns default value instead of None)
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/DFS, Graph] 1971. Find if Path Exists in Graph (0) | 2025.06.25 |
---|---|
[Neetcode/String Preprocessing ] Valid Palindrome (0) | 2025.06.24 |
[Neetcode/Brute-force, Hashmap] Two Sum (0) | 2025.06.24 |
[Leetcode/Stack] 1047. Remove All Adjacent Duplicates In String (0) | 2025.06.11 |
[CodePath] Unit 1: Strings and Arrays - Unique (0) | 2025.06.11 |