Time Complexity: O(n) Space Complexity: O(n)
(int[] nums, int k)
| 95 | * Space Complexity: O(n) |
| 96 | */ |
| 97 | public int[] topKFrequent(int[] nums, int k) { |
| 98 | Map<Integer, Integer> count = new HashMap<>(); |
| 99 | List<Integer> bucket[] = new ArrayList[nums.length + 1]; |
| 100 | |
| 101 | for (int num : nums) |
| 102 | count.merge(num, 1, Integer::sum); |
| 103 | |
| 104 | for (int key : count.keySet()){ |
| 105 | int freq = count.get(key); |
| 106 | if (bucket[freq] == null) |
| 107 | bucket[freq] = new ArrayList<>(); |
| 108 | bucket[freq].add(key); |
| 109 | } |
| 110 | |
| 111 | int index = 0; |
| 112 | int[] res = new int[k]; |
| 113 | for (int i = nums.length; i >= 0; i--) |
| 114 | if (bucket[i] != null) |
| 115 | for (int val : bucket[i]){ |
| 116 | res[index++] = val; |
| 117 | if(index == k) |
| 118 | return res; |
| 119 | } |
| 120 | return res; |
| 121 | } |
| 122 |