Given a list and a number k, print out the top k most repeating elements in the list.
1. Use hashmap to store the pair of number and count.
2. Use priority queue to store the hash node based on the value of each hash node, using comparator to define the priority queue.
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
public class Solution {
public static void findKElements(List<Integer> list, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.containsKey(list.get(i))) {
map.put(list.get(i), map.get(list.get(i)) + 1);
}
else
map.put(list.get(i), 1);
}
Comparator<Entry<Integer, Integer>> cmp;
cmp = new Comparator<Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> e1, Entry<Integer, Integer> e2) {
return e2.getValue() - e1.getValue();
}
};
Queue<Entry<Integer, Integer>> pq = new PriorityQueue<Entry<Integer, Integer>>(map.size(), cmp);
Iterator<Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
pq.offer(it.next());
}
for (int i = 0; i < k; i++) {
System.out.println(pq.poll().getKey());
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(0);
list.add(0);
list.add(0);
list.add(1);
list.add(1);
list.add(1);
list.add(1);
list.add(2);
list.add(2);
findKElements(list, 2);
}
}