File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import heapq
2+ from collections import Counter
3+
4+ class Solution :
5+ def topKFrequent (self , nums : list [int ], k : int ) -> list [int ]:
6+ """๋ฐ๋ณต๋๋ ํ์๊ฐ ๋์ ์์ผ๋ก Top k์ธ ์ซ์๋ค์ ์ฐพ๋ ํจ์
7+
8+ ๋ฐฉ๋ฒ
9+ 1. ์ ์ฒด ๋ชฉ๋ก์ ์ํํ๋ฉด์, ๊ฐ ์ซ์๊ฐ ๋ช ๋ฒ ๋์ค๋์ง ์ธ์ด, dict map ๋ง๋ค๊ธฐ.
10+ ์ดํ value ๊ฐ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํด, ์์ k๊ฐ๋ฅผ ๋ฐํํ๋ ๋ฐฉ๋ฒ => O(n) + O(n log n) => O(n log n)
11+ 2. 1๋ฒ์ ๋ฐฉ๋ฒ์์ dict map์ ๋ง๋๋ ๊ฑธ, python ๋ด์ฅ ๋ชจ๋์ธ Counter๋ก ๋์ฒดํ๊ธฐ.
12+ Counter๊ฐ ์ฝ๊ฐ ๋ ๋น ๋ฆ; C implementation์ด๊ธฐ ๋๋ฌธ.
13+ 3. 1๋ฒ ๋ฐฉ๋ฒ์ sorted ๋์ , heapq ๋ชจ๋์ nlargest ํจ์๋ฅผ ์ด์ฉํ๊ธฐ.
14+ ์ ์ฒด ๋ชฉ๋ก์ ์ํํ์ง ์๊ณ , top k์ ํด๋นํ๋ ๊ฐ๋ง ํ์
ํ๊ธฐ์ ํจ์จ์ ์. O(n) + O(n log k) => O(n log k)
15+ 4. quick select ์๊ณ ๋ฆฌ์ฆ. O(n) + O(n) => O(n); ํด๋น ๋ฌธ์ ์ ๊ตฌํํ์ง ๋ชปํจ.
16+
17+ Args:
18+ nums (list[int]): ์ ๋ ฌ๋์ง ์์ ์ค๋ณต ํฌํจ ์ ์ ๋ฐฐ์ด
19+ k (int): Top k์ ๊ฐ์
20+
21+ Returns:
22+ list[int]: Top k์ ํด๋นํ๋ ์ซ์๋ค์ ๋ฆฌ์คํธ
23+ """
24+ if len (nums ) <= 1 :
25+ return nums
26+ count = Counter (nums )
27+ return heapq .nlargest (k , count .keys (), key = count .get )
You canโt perform that action at this time.
0 commit comments