Created
April 5, 2026 06:27
-
-
Save ksamirdev/e1751cf8e740d0c1973e6cd0a3ba5277 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution: | |
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | |
| # lets use the bucket sort | |
| # dict | |
| # count: [0, 1, 2, 3] | |
| # freq: [[], [3], [2], [1]] | |
| # basically values how many time have appeared | |
| # (index is count) | |
| n = len(nums) | |
| count = {} | |
| freq = [[] for i in range(n + 1)] | |
| for n in nums: | |
| count[n] = 1 + count.get(n, 0) | |
| for n, c in count.items(): | |
| freq[c].append(n) | |
| res = [] | |
| for i in range(len(freq) - 1, 0, -1): | |
| for n in freq[i]: | |
| res.append(n) | |
| if len(res) == k: | |
| return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment