Skip to content

Commit c96a6e9

Browse files
author
sangbeenmoon
committed
solved top-k-frequent-elements.
1 parent e735f08 commit c96a6e9

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# idea
2+
# 1. ๋นˆ๋„์ˆ˜๋ฅผ dict ์— ์ €์žฅํ•œ๋‹ค.
3+
# 2. ๋นˆ๋„์ˆ˜ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.
4+
# 3. 2์—์„œ ์ •๋ ฌํ•œ entry ์ค‘ 1๋ฒˆ์งธ, 2๋ฒˆ์งธ, ... k ๋ฒˆ์งธ key ๊ฐ’์„ ๋ชจ์•„์„œ List ๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
5+
# time : O(nlogn)
6+
# space : O(n)
7+
class Solution:
8+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
9+
count_dict = {}
10+
11+
for num in nums:
12+
if num in count_dict:
13+
count_dict[num] = count_dict[num] + 1
14+
else:
15+
count_dict[num] = 1
16+
17+
tuple_list = []
18+
19+
for (count_key, count_value) in count_dict.items():
20+
tuple_list.append((count_key, count_value))
21+
22+
sorted_tuple_list = sorted(tuple_list, key=lambda x: x[1], reverse=True)
23+
answer = []
24+
25+
for i in range(k):
26+
answer.append(sorted_tuple_list[i][0])
27+
28+
return answer
29+
30+
31+

0 commit comments

Comments
ย (0)