Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
- You may assume k is always valid, 1 ? k ? number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
一刷
题解:利用bucket sort的思路,先统计词频,然后再将frequency作为index访问得到具体的词。从大到小的前k个。
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
for (int n : nums) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
}
for (int key : frequencyMap.keySet()) {
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
bucket[frequency].add(key);
}
List<Integer> res = new ArrayList<>();
for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
if (bucket[pos] != null) {
res.addAll(bucket[pos]);
}
}
return res;
}
}
二刷
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> result = new ArrayList();
if (nums.length == 0 || nums.length == 1){
if(k == 1){
result.add(nums[0]);
}
return result;
}
PriorityQueue<Node> pq = new PriorityQueue<Node>(k,new NodeComparator());
Arrays.sort(nums);
int count = 1 ;
for (int i = 1; i< nums.length;i++){
if (nums[i] != nums[i-1]){
pq.add(new Node(nums[i-1],count));
count = 1;
}else{
count++;
}
}
pq.add(new Node(nums[nums.length-1],count));
count = 0;
while(count++<k){
result.add(pq.poll().key);
}
return result;
}
}
class Node{
int key;
int count;
Node(int key, int count){
this.key = key;
this.count = count;
}
}
class NodeComparator implements Comparator<Node>{
public int compare(Node a, Node b){
if (a.count > b.count ){
return -1;
}else if (a.count < b.count){
return 1;
}else{
return 0;
}
}
}