Skip to content

Commit 273a4af

Browse files
committed
feat: improve time complexity for "Top K Frequent Elements"
O(nlogn)μ—μ„œ O(nlogk)둜 μ‹œκ°„λ³΅μž‘λ„ κ°œμ„ 
1 parent b149e2d commit 273a4af

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Constraints:
3+
4+
1 <= nums.length <= 10^5
5+
-10^4 <= nums[i] <= 10^4
6+
k is in the range [1, the number of unique elements in the array].
7+
8+
nums λ°°μ—΄μ—μ„œ μ›μ†Œλ“€μ˜ λΉˆλ„μˆ˜ 쀑, κ°€μž₯ λΉˆλ„μˆ˜κ°€ 높은 k개의 μˆ˜λ“€ λ°˜ν™˜
9+
10+
Time Complexity: O(klogn)
11+
12+
λ‚΄λΆ€μ μœΌλ‘œ μ •λ ¬λ˜λŠ” O(logn)을 κ°€μ§€λŠ” μ΅œμ†Œ νž™ μ‚¬μš©?
13+
14+
μš°μ„  λΉˆλ„μˆ˜ 사전에 기둝 -> dict[숫자] = λΉˆλ„μˆ˜ O(n)
15+
κ·Έ λ‹€μŒ, 사전.items() λŒλ©΄μ„œ heap 에 k개 만큼 λ„£κΈ° O(k * logn)
16+
17+
k개 만큼 μš°μ„ μˆœμœ„ 큐에 λ„£κΈ° (-λΉˆλ„μˆ˜, 숫자) -> νŠœν”Œ λ„£μœΌλ©΄ 첫번쨰 μ›μ†ŒκΈ°μ€€μœΌλ‘œ 정렬됨
18+
19+
그리고, λ‚˜λ¨Έμ§€ 사전.items() 만큼 for i in range(k + 1, n) 만큼만 돌기
20+
-> λ§Œμ•½ νž™μ˜ 맨 μ•ž 값보닀 μž‘μœΌλ©΄ λ„£κ³ , μ•„λ‹ˆλΌλ©΄ pass
21+
22+
Space Complexity: O(n)
23+
24+
nums만큼 사전에 λΉˆλ„μˆ˜ μ €μž₯
25+
26+
# κ°„κ³Όν•œ 사싀
27+
첫 k개만 μš°μ„ μˆœμœ„ 큐에 λ„£κ³ , λ‚˜λ¨Έμ§€ n - k 만큼 λŒλ•Œ,
28+
νž™μ˜ 맨 μ•ž 값보닀 μž‘κ±°λ‚˜ 같을 λ•Œ -> 맨 μ•ž 값을 λΉΌλ©΄ μ•ˆλ¨!! 그게 μ •λ‹΅ 수 쀑 ν•˜λ‚˜μΌ 수 있음
29+
30+
31+
μ•„λΏ”μ‹Έ..맨 μ•ž κ°’λ§Œ μ •λ ¬λ˜μ–΄μžˆλŠ” μƒνƒœλΌ, λ§ˆμ§€λ§‰ κ°’ λ°˜ν™˜ μ‹œ heappop으둜 ν•΄μ€˜μ•Όν• λ“―!
32+
λ‹¨μˆœνžˆ for i in range(k) ν•΄μ„œ 맨 μ•ž k 개λ₯Ό λ°˜ν™˜ν•˜λ©΄ μ •λ ¬λ˜μ§€ μ•Šμ€ μƒνƒœμ—μ„œ 값을 λ½‘μ•„λ‚΄λ―€λ‘œ 틀릴 수 있음
33+
34+
# λ°˜λ‘€
35+
36+
[2,3,4,1,4,0,4,-1,-2,-1]
37+
38+
맨 μ•žμ˜ κ°’μ΄λž‘λ§Œ λΉ„κ΅ν•˜λ‹€λ³΄λ‹ˆ, μ΅œλŒ€ λΉˆλ„μˆ˜ 값은 μ •ν™•νžˆ λ‚˜μ˜€λŠ”λ° 두 번째 이후 값이 첫 번째 값보닀 μž‘μ§€ μ•Šμ•„μ„œ νž™μ— λͺ» λ“€μ–΄μ˜¨λ‹€..
39+
κ·Έλž˜μ„œ, 맨 μ•žμ˜ κ°’ 비ꡐ 둜직 μ—†μ•°!!
40+
41+
ν•˜μ§€λ§Œ, νž™ λ‚΄ μ›μ†Œλ₯Ό k개λ₯Ό μœ μ§€ λͺ»ν•΄μ„œ μ •λ ¬ μ‹œκ°„μ΄ log N 이 λ˜μ–΄λ²„λ¦Ό..
42+
-> heap의 μ‚¬μ΄μ¦ˆλ₯Ό k둜 μœ μ§€ν•˜λ©΄μ„œ μž‘μ€ λΉˆλ„ μˆ˜λΆ€ν„° μ œκ±°ν•˜λ©΄,
43+
κ²°κ΅­ heap μ•ˆμ—λŠ” κ°€μž₯ 많이 λ“±μž₯ν•œ k개의 μ›μ†Œλ§Œ λ‚¨λŠ”λ‹€.
44+
"""
45+
46+
from collections import defaultdict
47+
from heapq import heappush, heappop
48+
49+
50+
class Solution:
51+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
52+
freq_dict = defaultdict(int)
53+
min_heap = []
54+
ret = []
55+
56+
for n in nums:
57+
freq_dict[n] += 1
58+
59+
for key, value in freq_dict.items():
60+
heappush(min_heap, (value, key))
61+
if len(min_heap) > k:
62+
heappop(min_heap)
63+
64+
for _ in range(k):
65+
ret.append(heappop(min_heap)[1])
66+
67+
return ret

0 commit comments

Comments
Β (0)