Skip to content

Commit dc6b6ad

Browse files
committed
Solve: topKFrequent
1 parent 269e6ab commit dc6b6ad

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+

0 commit comments

Comments
ย (0)