|
| 1 | +from collections import Counter |
| 2 | +from typing import List |
| 3 | +from unittest import TestCase, main |
| 4 | + |
| 5 | + |
| 6 | +class Solution: |
| 7 | + def topKFrequent(self, nums: List[int], k: int) -> List[int]: |
| 8 | + return self.solve_3(nums, k) |
| 9 | + |
| 10 | + """ |
| 11 | + Runtime: 82 ms (Beats 87.87%) |
| 12 | + Analyze Complexity: O(n log n) |
| 13 | + most_common의 정렬이 O(n log n) |
| 14 | + Memory: 21.13 MB (Beats 60.35%) |
| 15 | + """ |
| 16 | + def solve_1(self, nums: List[int], k: int) -> List[int]: |
| 17 | + return [key for key, value in Counter(nums).most_common(k)] |
| 18 | + |
| 19 | + """ |
| 20 | + Runtime: 88 ms (Beats 62.46%) |
| 21 | + Analyze Complexity: O(n log n) |
| 22 | + counter 생성에 O(n), 정렬에 O(n log n), slicing에 O(k) |
| 23 | + Memory: 21.17 MB (Beats 60.35%) |
| 24 | + """ |
| 25 | + def solve_2(self, nums: List[int], k: int) -> List[int]: |
| 26 | + counter = {} |
| 27 | + for num in nums: |
| 28 | + counter[num] = 1 + counter.get(num, 0) |
| 29 | + |
| 30 | + sorted_counter = sorted(counter.items(), key=lambda item: -item[1]) |
| 31 | + return [item[0] for item in sorted_counter[:k]] |
| 32 | + |
| 33 | + |
| 34 | + """ |
| 35 | + Runtime: 81 ms (Beats 90.60%) |
| 36 | + Analyze Complexity: O(n) |
| 37 | + counter 생성이 O(n), counter_matrix 생성이 O(n), reversed는 O(1), early-return으로 O(k) |
| 38 | + Memory: 22.10 MB (Beats 12.57%) |
| 39 | + """ |
| 40 | + def solve_3(self, nums: List[int], k: int) -> List[int]: |
| 41 | + counter = {} |
| 42 | + for num in nums: |
| 43 | + counter[num] = 1 + counter.get(num, 0) |
| 44 | + |
| 45 | + counter_matrix = [[] for _ in range(len(nums) + 1)] |
| 46 | + for key, val in counter.items(): |
| 47 | + counter_matrix[val].append(key) |
| 48 | + |
| 49 | + result = [] |
| 50 | + for num_list in reversed(counter_matrix): |
| 51 | + for num in num_list: |
| 52 | + result.append(num) |
| 53 | + if len(result) >= k: |
| 54 | + return result |
| 55 | + else: |
| 56 | + return result |
| 57 | + |
| 58 | + |
| 59 | +class _LeetCodeTCs(TestCase): |
| 60 | + def test_1(self): |
| 61 | + nums = [1, 1, 1, 2, 2, 3] |
| 62 | + k = 2 |
| 63 | + output = [1, 2] |
| 64 | + self.assertEqual(Solution.topKFrequent(Solution(), nums, k), output) |
| 65 | + |
| 66 | + def test_2(self): |
| 67 | + nums = [1] |
| 68 | + k = 1 |
| 69 | + output = [1] |
| 70 | + self.assertEqual(Solution.topKFrequent(Solution(), nums, k), output) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == '__main__': |
| 74 | + main() |
0 commit comments