Skip to content

Commit c9ffedf

Browse files
committed
add top-k-frequent-elements solution
1 parent ea4ed88 commit c9ffedf

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/top-k-frequent-elements/
4+
5+
[Brain Storming]
6+
가장 자주 사용되는 요소 k개를 반환한다.
7+
8+
1<= nums.length <= 10^5
9+
O(n^2) time complexity일 경우 시간 초과 발생
10+
11+
[Plan]
12+
1. nums를 순회하면서 Hash Table에 key:element value:count 저장한다.
13+
2. nums를 순회하면서 Heap에 (count, element)를 count를 기준으로 Max Heap 형태로 저장한다.
14+
3. Max Heap에서 k개 만큼 pop한다.
15+
16+
[Complexity]
17+
N: nums.length, K: k
18+
heapq.heapify(heap): O(N)
19+
heapq.heappop(heap): log(N)
20+
21+
Time: O(N + (K * log(N)))
22+
Space: O(N + K)
23+
* num_to_count_map: O(N)
24+
* heap: O(N)
25+
* answer: O(K)
26+
27+
28+
"""
29+
30+
import heapq
31+
32+
class Solution(object):
33+
def topKFrequent(self, nums, k):
34+
num_to_count_map = {}
35+
for num in nums:
36+
num_to_count_map[num] = num_to_count_map.get(num, 0) + 1
37+
38+
heap = []
39+
for num, count in num_to_count_map.items():
40+
heap.append((-count, num))
41+
heapq.heapify(heap)
42+
43+
answer = []
44+
for _ in range(k):
45+
negative_count, frequent_num = heapq.heappop(heap) # log(N)
46+
answer.append(frequent_num)
47+
return answer
48+
49+
solution = Solution()
50+
51+
# Normal Case
52+
print(solution.topKFrequent([1,1,1,2,2,3], 2) == [1, 2])
53+
print(solution.topKFrequent([1], 1) == [1])
54+
55+

0 commit comments

Comments
 (0)