LeetCode Problem Link: https://leetcode.com/problems/top-k-frequent-elements/description/
Solution:
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// Count the frequency.
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
for (int num : nums) {
counter.put(num, counter.getOrDefault(num, 0) + 1);
}
// Store the frequency into buckets.
List<Integer>[] buckets = new List[nums.length + 1 - (counter.size() - 1)];
for (int key : counter.keySet()) {
int count = counter.get(key);
if (buckets[count] == null) buckets[count] = new ArrayList<Integer>();
buckets[count].add(key);
}
// Get top K buckets.
List<Integer> results = new ArrayList<Integer>();
for (int i = buckets.length - 1, topK = 0; topK < k && i >= 0; i--) {
if (buckets[i] != null) {
results.addAll(buckets[i]);
topK += buckets[i].size();
}
}
return results;
}
}
Complexity:
O(n) Time complexity.
O(n) Space complexity.
Result:
Run time 24ms
Beats 87% users
Solution:
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// Count the frequency.
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
for (int num : nums) {
counter.put(num, counter.getOrDefault(num, 0) + 1);
}
// Store the frequency into buckets.
List<Integer>[] buckets = new List[nums.length + 1 - (counter.size() - 1)];
for (int key : counter.keySet()) {
int count = counter.get(key);
if (buckets[count] == null) buckets[count] = new ArrayList<Integer>();
buckets[count].add(key);
}
// Get top K buckets.
List<Integer> results = new ArrayList<Integer>();
for (int i = buckets.length - 1, topK = 0; topK < k && i >= 0; i--) {
if (buckets[i] != null) {
results.addAll(buckets[i]);
topK += buckets[i].size();
}
}
return results;
}
}
Complexity:
O(n) Time complexity.
O(n) Space complexity.
Result:
Run time 24ms
Beats 87% users
留言
張貼留言