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+
2+ # 6๊ธฐ
3+ # class Solution:
4+ # # dictionary use
5+ # def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+ # result = {} # key: ์์, value: ๋ฑ์ฅ ํ์
7+ # for n in nums:
8+ # if n in result:
9+ # result[n] = result[n] + 1
10+ # else:
11+ # result[n] = 1
12+
13+ # # ๊ฐ์ฅ ์์ฃผ ๋ฑ์ฅํ ์์ k๊ฐ ๋ฐํ
14+ # return sorted(result.keys(), key=lambda x: result[x], reverse=True)[:k]
15+
16+ # 7๊ธฐ
117class Solution :
2- # dictionary use
318 def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
4- result = {} # key: ์์, value: ๋ฑ์ฅ ํ์
5- for n in nums :
6- if n in result :
7- result [n ] = result [n ] + 1
19+ # 1. Count frequency of each number
20+ freq = {}
21+
22+ for num in nums :
23+ if num not in freq :
24+ freq [num ] = 1
825 else :
9- result [n ] = 1
26+ freq [num ] += 1
27+
28+ # 2. Sort by frequency in descending order
29+ sorted_items = sorted (freq .items (), key = lambda item : item [1 ], reverse = True )
30+
31+ # 3. Take the first k elements
32+ result = []
33+ for i in range (k ):
34+ result .append (sorted_items [i ][0 ])
1035
11- # ๊ฐ์ฅ ์์ฃผ ๋ฑ์ฅํ ์์ k๊ฐ ๋ฐํ
12- return sorted (result .keys (), key = lambda x : result [x ], reverse = True )[:k ]
36+ return result
You canโt perform that action at this time.
0 commit comments