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
+ ๏ปฟ #ํด์
2
+ #nums๋ฅผ dictionary๋ก ์ ํํ๋ค. nums์ ๊ธฐ์กด element๊ฐ key, element์ ๊ฐฏ์๋ฅผ value๊ฐ์ผ๋ก ์ง์ ํ๋ค.
3
+ #value๊ฐ์ด ํฐ ์์๋๋ก dictionary์ ์์๋ฅผ ์ ๋ ฌํ๋ค
4
+ #๊ทธ์ค 0์์ k-1๊น์ง์ key๊ฐ๋ง์ ๋ฐํํ๋ค.
5
+
6
+ #Big O
7
+ #N: ์ฃผ์ด์ง list์ ๊ธธ์ด nums (Length of the input list nums)
8
+ #M: count ๋์
๋๋ฆฌ์ ๊ณ ์ ํ key ์ ๊ฐฏ์
9
+
10
+ #Time Complexity: O(NLogN)
11
+ #- count: N์ ๊ธธ์ด์ ๊ธฐ๋ฐํ์ฌ ์์ฑ๋๋ค : O(N)
12
+ #- sorted_count: ํ์ด์ฌ์ sorted ๋ฉ์๋๋ Timesort ์๊ณ ๋ฆฌ์ฆ ๊ธฐ๋ฐ์ ๋น๊ต ๊ธฐ๋ฐ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ
13
+ # ๋ฆฌ์คํธ์ ๊ธธ์ด๊ฐ M์ด๋ฉด sorted()๋ ์์๋ค์ ์ชผ๊ฐ๊ณ ๋ณํฉํ์ฌ ์ ๋ ฌํ๋ค. ๋๋ต M๊ฐ์ ์์๋ฅผ logM๋ฒ ๋น๊ต
14
+
15
+ #Space Complexity: O(N)
16
+ #- count: M๊ฐ์ ๊ธฐ๋ฐํ์ฌ Dictionary ๊ณต๊ฐ ์ ์ฅ: O(M)
17
+ #- sorted_count: count.items์ ๊ฐฏ์์ ๊ธฐ๋ฐํ์ฌ ๊ณต๊ฐ ์ ์ฅ : O(M)
18
+ #- dic_count: ์์ ์์ ๊ฐฏ์(k๊ฐ) ๋งํผ ์ ์ฅ : O(k)
19
+ #- ์ต์ข
: O(N) + O(M) + O(k): k๋ ์ต๋ M๊ฐ ๋งํผ ๊ฐ๋ฅํ๊ณ M์ ์ต๋ N๊ฐ๋งํผ ๊ฐ๋ฅํ๋ค.
20
+
21
+ class Solution (object ):
22
+ def topKFrequent (self , nums , k ):
23
+ """
24
+ :type nums: List[int]
25
+ :type k: int
26
+ :rtype: List[int]
27
+ """
28
+
29
+ #Create dictionary which have a key(element of nums) and value(count num of the element)
30
+ count = {}
31
+ for i in nums :
32
+ try : count [i ] += 1
33
+ except : count [i ] = 1
34
+
35
+ #Sort depends on the value descending order
36
+ sorted_count = sorted (count .items (),key = lambda x :x [1 ],reverse = True )
37
+ #k๊น์ง์ ์์๋ง์ dictionary data type์ผ๋ก convert
38
+ dic_count = dict (sorted_count [:k ])
39
+ #Return keys
40
+ return dic_count .keys ()
41
+
42
+
43
+
You canโt perform that action at this time.
0 commit comments