File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+ from heapq import nlargest
3+
4+ """
5+ ๋ฌธ์ ์ค๋ช
:
6+ ์ด ๋ฌธ์ ๋ ์ฃผ์ด์ง k๋ฒ์งธ ๋งํผ ๋น๋์๊ฐ ๋์ ๊ฐ๋ค์ ๋ฐํํ๋ ๋ฌธ์
7+ ๋น๋์ ์ฒดํฌ ํ, ๋ฐํ ๊ฐ ์์๋ ์๊ด ์๋ค๊ณ ํ์ผ๋ heap ์ฌ์ฉ
8+
9+ {
10+ 1: 3, # 1์ด 3๋ฒ ๋ฑ์ฅ
11+ 2: 2, # 2๊ฐ 2๋ฒ ๋ฑ์ฅ
12+ 3: 1, # 3์ด 1๋ฒ ๋ฑ์ฅ
13+ }
14+
15+ ๋น๋์ ๊ธฐ์ค์ผ๋ก k๋ฒ์งธ๋งํผ ํฐ ๊ฐ์ ๋ฐํ
16+ """
17+
18+ class Solution :
19+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
20+ count_dic = {}
21+
22+ for num in nums :
23+ if num in count_dic :
24+ count_dic [num ] += 1
25+ else :
26+ count_dic [num ] = 1
27+
28+ # ๋น๋์๊ฐ ํฐ ์์๋๋ก k๊ฐ๋ฅผ ๋ฐํ
29+ return nlargest (k , count_dic , key = count_dic .get )
30+
31+ """
32+ ์๊ฐ๋ณต์ก๋: O(n log k)
33+ - ๋์
๋๋ฆฌ O(n) + heap์ ์ฌ์ฉํด์ k๋ฒ์งธ ์์๊น์ง ๋ฐํ O(n log k) = O(n log k)
34+
35+ ๊ณต๊ฐ๋ณต์ก๋: O(n)
36+ - ์ต๋ n๊ฐ์ ์๋ก ๋ค๋ฅธ ์ซ์๊ฐ ์์ ์ ์๊ณ , O(n)
37+ - heap์ ์ต๋ k๊ฐ๋ง ์ ์ฅ -> O(k)
38+ ์ ์ฒด์ ์ผ๋ก O(n)
39+ """
40+
41+
42+
43+
You canโt perform that action at this time.
0 commit comments